ernewston
ernewston

Reputation: 1015

Firebase One-time Functions

I'm sure these are common scenarios, but after researching some hours, I couldn't really find what the common practice is. Maybe someone with more experience in Firebase can point me to the right direction.

I have two particular scenarios:

1. Code that runs once

Example 1: adding new data to all users in firestore, which is needed for a new feature
Example 2: start duplicating data into existing documents

I currently write the code in a cloud function, and run it on a firestore event (onUpdate of a "hidden" document) and then I immediately delete the function if everything goes well.

I also increase the timeout and memory for this function, as the idea is to potentially update millions of documents.

2. Manually trigger a function from the firebase console (or command line)

Example: Give a user admin privileges in the app (function that sets custom claims and firestore data). We don't have time to implement a back-office, so doing this from the firebase web portal/console would be ideal, specifying the user id.

My current solution is to use a https function, and run it from the GCP portal (on the function's "Testing" tab, being able to pass a json). BUT the function can be triggered publicly, which I don't really like...

What are the common practices for these scenarios?

Upvotes: 9

Views: 2559

Answers (2)

Kevin Renskers
Kevin Renskers

Reputation: 5940

To expand on my comment: if you want to create a node script to run one-off code, you just write your JS code like for any cloud function but simply run it immediately. Something like this.

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

db.collection('users')
  .where('myField', '==', true)
  .get()
  .then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
      // update doc
    });
  });

If you save this as script.js and execute it with node script.js you’ll be pointed towards downloading a JSON file with credentials. Follow the instructions and you can then run the script again and now you’re running your own code on Firestore, from the command line.

Upvotes: 10

Doug Stevenson
Doug Stevenson

Reputation: 317740

For administrative type operations, you're better off just running them on your desktop or some other server you control. Cloud Functions is not well suited for long running operations, or things that must just happen once on demand.

Case 1 really should be managed by a standalone program or script that you can monitor by running it on your desktop.

Case 2 can be done a number of ways, such as building your own admin web site. But you might find it easiest to mirror the contents of a document to custom claims using a Firestore trigger. Read this: https://medium.com/firebase-developers/patterns-for-security-with-firebase-supercharged-custom-claims-with-firestore-and-cloud-functions-bb8f46b24e11

Upvotes: 4

Related Questions