UNPKG

node-firestore-import-export

Version:
72 lines (71 loc) 3.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const firestore_helpers_1 = require("./firestore-helpers"); const helpers_1 = require("./helpers"); const importData = (data, startingRef) => { const dataToImport = Object.assign({}, data); if (firestore_helpers_1.isLikeDocument(startingRef)) { if (!dataToImport.hasOwnProperty('__collections__')) { throw new Error('Root or document reference doesn\'t contain a __collections__ property.'); } const collections = dataToImport['__collections__']; delete (dataToImport['__collections__']); const collectionPromises = []; for (const collection in collections) { if (collections.hasOwnProperty(collection)) { collectionPromises.push(setDocuments(collections[collection], startingRef.collection(collection))); } } if (firestore_helpers_1.isRootOfDatabase(startingRef)) { return Promise.all(collectionPromises); } else { const documentID = startingRef.id; const documentData = {}; documentData[documentID] = dataToImport; const documentPromise = setDocuments(documentData, startingRef.parent); return documentPromise.then(() => Promise.all(collectionPromises)); } } else { return setDocuments(dataToImport, startingRef); } }; const setDocuments = (data, startingRef) => { console.log(`Writing documents for ${startingRef.path}`); if ('__collections__' in data) { throw new Error('Found unexpected "__collection__" in collection data. Does the starting node match' + ' the root of the incoming data?'); } const collections = []; const chunks = helpers_1.array_chunks(Object.keys(data), 500); const chunkPromises = chunks.map((documentKeys) => { const batch = startingRef.firestore.batch(); documentKeys.map((documentKey) => { if (data[documentKey]['__collections__']) { Object.keys(data[documentKey]['__collections__']).map(collection => { collections.push({ path: startingRef.doc(documentKey).collection(collection), collection: data[documentKey]['__collections__'][collection] }); }); delete (data[documentKey]['__collections__']); } const documentData = helpers_1.unserializeSpecialTypes(data[documentKey], startingRef.firestore); batch.set(startingRef.doc(documentKey), documentData, { merge: true }); }); return batch.commit(); }); return Promise.all(chunkPromises) .then(() => { return collections.map((col) => { return setDocuments(col.collection, col.path); }); }) .then(subCollectionPromises => Promise.all(subCollectionPromises)) .catch(err => { console.log(err); }); }; exports.setDocuments = setDocuments; exports.default = importData;