Created
August 15, 2018 09:40
-
-
Save olegdater/5f1cc71cab1e848188a8eb46776e04d3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { remoteConfig } from './index'; | |
const admin = require('../functions/node_modules/firebase-admin'); | |
const _ = require('../functions/node_modules/lodash'); | |
const serviceAccount = require('../configs//firebase/service-key.development.json'); | |
admin.initializeApp({ | |
credential: admin.credential.cert(serviceAccount), | |
// databaseURL: "https://<your-database-name>.firebaseio.com" | |
}); | |
/** | |
* Data is a collection if | |
* - it has a odd depth | |
* - contains only objects or contains no objects. | |
*/ | |
function isCollection(data) { | |
let isCollectionFlag = true; | |
if ( | |
typeof data !== 'object' || | |
_.isEmpty(data) | |
) { | |
isCollectionFlag = false; | |
} | |
Object.keys(data).forEach((key) => { | |
if (typeof data[key] !== 'object' || data[key] == null) { | |
// If there is at least one non-object item i its data then it cannot be collection. | |
isCollectionFlag = false; | |
} | |
}); | |
return isCollectionFlag; | |
} | |
function upload(data, path) { | |
return admin.firestore() | |
.doc(path.join('/')) | |
.set(data) | |
.then(() => console.log(`Document ${path.join('/')} uploaded.`)) | |
.catch(() => console.error(`Could not write document ${path.join('/')}.`)); | |
} | |
/** | |
* | |
*/ | |
async function resolve(data, path = []) { | |
if (path.length > 0 && path.length % 2 === 0) { | |
// Document's length of path is always even, however, one of keys can actually be a collection. | |
// Copy an object. | |
const documentData = Object.assign({}, data); | |
Object.keys(data).forEach((key) => { | |
// Resolve each collection and remove it from document data. | |
if (isCollection(data[key])) { | |
// Remove a collection from the document data. | |
delete documentData[key]; | |
// Resolve a colleciton. | |
resolve(data[key], [...path, key]); | |
} | |
}); | |
// If document is empty then it means it only consisted of collections. | |
if (!_.isEmpty(documentData)) { | |
// Upload a document free of collections. | |
await upload(documentData, path); | |
} | |
} else { | |
// Collection's length of is always odd. | |
Object.keys(data).forEach(async (key) => { | |
// Resolve each collection. | |
await resolve(data[key], [...path, key]); | |
}); | |
} | |
} | |
resolve({ | |
remoteConfig, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment