Jeremy Belolo
Jeremy Belolo

Reputation: 4539

Firestore automatic backup using new Pub/Sub function

So for a few months now Firestore supports https://firebase.googleblog.com/2019/04/schedule-cloud-functions-firebase-cron.html

On the guide to schedule data exports, the recommended way to do it is through App Engine : https://firebase.google.com/docs/firestore/solutions/schedule-export

I was wondering if it was possible to do it directly from a cloud function, scheduled. If so, what would be the way to go? How to use the googleapis, specifically how to configure the scopes, how to call exportDocuments REST resource...

Upvotes: 1

Views: 606

Answers (1)

cbdeveloper
cbdeveloper

Reputation: 31385

I havent built the function yet, but so I far I've managed to do it using this script I wrote with a service account key.

firestoreBackup.js

import * as admin from 'firebase-admin';
import serviceAccount from './serviceAccounts/your-service-account-key.js';

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://your-app.firebaseio.com"
});

const client = new admin.firestore.v1.FirestoreAdminClient({});

async function doFirestoreBackup() {
  try {
    const response = await client.exportDocuments({
      name: client.databasePath('your-project-name','(default)'),
      outputUriPrefix: 'gs://your-project.appspot.com/firestore-backups/2019-08-25-T-12H00/'  // THIS IS YOUR BUCKET. YOU CAN CHOOSE THE FOLDER
    });
    console.log(response);
  }
  catch(err) {
    console.log(err.msg);
  }
}

doFirestoreBackup();

I'm using babel-node to execute it:

// TO RUN THE SCRIPT (NAVIGATE TO FOLDER)
C:\...\src\adminScripts\> npx babel-node firestoreBackup.js

Upvotes: 2

Related Questions