Last active
February 16, 2021 09:58
-
-
Save toonverbeek/756290e09281e26fa89e3b73968be80d to your computer and use it in GitHub Desktop.
Script to dump a firestore collection and import it to your local firestore emulator
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
const { backup, restore, initializeApp } = require('firestore-export-import') | |
const fs = require('fs-extra'); | |
const args = process.argv.slice(2); | |
if (args.includes('import')) { | |
process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080'; | |
} | |
// Get this from your firebase project settings | |
const serviceAccount = require('./adminsdk.json') | |
// Initiate Firebase App | |
// appName is optional, you can omit it. | |
const appName = '[DEFAULT]' | |
initializeApp(serviceAccount, appName) | |
const options = { | |
docsFromEachCollection: 10, // limit number of documents when exporting | |
refs: ['refKey'], // reference Path | |
} | |
// which collection to import/export | |
const collectionName = 'users'; | |
async function main() { | |
if (args.includes('import')) { | |
if (process.env.FIRESTORE_EMULATOR_HOST === 'localhost:8080') { | |
console.log('restoring collection to emulator'); | |
await restore(`${collectionName}-backup-2021-01-25T14:36:47.527Z.json`); | |
} | |
} else if (args.includes('export')) { | |
console.log('creating backup'); | |
backup(collectionName).then((data) => { | |
const name = `${collectionName}-backup-${new Date().toISOString()}.json`; | |
fs.outputFile(name, JSON.stringify(data)); | |
console.log(`Copy this string to import: ${name}`); | |
}); | |
} else { | |
console.error('invalid command'); | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment