Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Created March 23, 2018 02:41
Show Gist options
  • Save hhimanshu/1a8718f61c61727d8452c3c109b2aa8a to your computer and use it in GitHub Desktop.
Save hhimanshu/1a8718f61c61727d8452c3c109b2aa8a to your computer and use it in GitHub Desktop.
import * as admin from "firebase-admin";
export const getFirebaseApp = (credentialsJsonFile, appName) => {
let fbAdmin = admin.initializeApp({
credential: admin.credential.cert(credentialsJsonFile)
}, appName);
return fbAdmin.firestore();
};
import {getFirebaseApp} from "./firebaseApi";
import fs from 'fs';
import readline from 'readline';
let sourceDb = getFirebaseApp('serviceAccountKeySource.json', 'source');
let destinationDb = getFirebaseApp('serviceAccountKeyDestination.json', 'destination');
let backupFileName = 'backup.txt';
/**
* TODO
* 1. backup filename should append date time in UTC
* 2. sourceDB JSON file should be input to the program
* 3. destinationDB JSON file should be input to the program
* 4. program should take command-line arguments for backup or restore (but not both)
* 5. Program should run from production build file. (not via npm run dev)
* @param sourceDb
*/
// https://cloud.google.com/nodejs/docs/reference/firestore/0.11.x/Firestore#getCollections
let backup = (sourceDb) => {
let stream = fs.createWriteStream(backupFileName);
sourceDb.getCollections().then(collectionsPromise => {
//console.log(`collectionsPromise length: ${collectionsPromise.length}`);
Promise.all(collectionsPromise)
.then(collectionsRef => {
// console.log(`collectionsRef length: ${collectionsRef.length}`);
return collectionsRef.map(collection => {
return collection.get();
});
}).then(collections => {
Promise.all(collections)
.then(querySnapshots => {
querySnapshots.map(querySnapshot => {
let docs = querySnapshot.docs;
docs.map(doc => {
let collectionId = `${doc.ref.parent.id}/`;
let collectionPath = `${doc.ref.path}/`;
let documentId = doc.id;
let document = JSON.stringify(doc.data());
let lineToWrite = {collectionId, collectionPath, documentId, document};
//console.log(lineToWrite);
stream.write(JSON.stringify(lineToWrite) + '\n');
});
});
stream.end();
});
});
});
};
let restore = (destinationDb, backupFile) => {
let lineReader = readline.createInterface({
input: fs.createReadStream(backupFile)
});
lineReader.on('line', function (line) {
let payload = JSON.parse(line);
// console.log('Line from file:', payload);
destinationDb.collection(payload.collectionId)
.doc(payload.documentId)
.set(JSON.parse(payload.document))
.then(writeResult => console.log(`Document written to ${payload.collectionId} at ${writeResult.writeTime}`));
});
};
// entry point
//backup(sourceDb);
restore(destinationDb, backupFileName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment