Skip to content

Instantly share code, notes, and snippets.

@gregfenton
Last active December 7, 2022 22:57
Show Gist options
  • Save gregfenton/f29ff47ab1c4563d12bcd69192fe485e to your computer and use it in GitHub Desktop.
Save gregfenton/f29ff47ab1c4563d12bcd69192fe485e to your computer and use it in GitHub Desktop.
Backup your Firestore db to a Firebase Storage bucket -- to be called from a Firebase Cloud Function (JavaScript/node)
const functions = require('firebase-functions');
const firestore = require('@google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
//
// Add config values with CLI command:
// firebase functions:config:set my_app_name='{"fsBackupBucket":"gs://my-fs-backup-bucket"}'
//
const config = functions.config();
export const backupToStorage = () => {
const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT;
const databaseName = client.databasePath(projectId, '(default)');
const bucketName = config.my_app_name.fsBackupBucket;
console.log(`firestoreBackup(): projectId is (${projectId})`);
console.log(`firestoreBackup(): databaseName is (${databaseName})`);
console.log(`firestoreBackup(): bucketName is (${bucketName})`);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucketName,
// Leave collectionIds empty to export all collections
// or set to a list of collection IDs to export,
// collectionIds: ['users', 'posts']
collectionIds: [],
})
.then((responses) => {
const response = responses[0];
console.log('Operation Name: ' + response['name']);
})
.catch((ex) => {
console.error(`Export operation failed: ${ex.message}\n${ex.stack}`);
throw new Error(`Export operation failed: ${ex.message}`);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment