简体   繁体   中英

Write to firebase database from cloud function triggered by PubSub

I'm trying to use a daily trigger to alter information in my Firebase database. I have a number of other cloud functions that work properly, but I can't seem to get this function to alter the database.

const admin = require('firebase-admin');
exports.daily_job = functions.pubsub.topic('daily-tick').onPublish((event) => {
  console.log("This job is run every day!");
  const databaseRef = admin.database().ref('/accountActions/dailyDeletion');
  databaseRef.child('delete').set("Data has been deleted!");
  return "End of database clearing";
});

This is the code I've been testing to see if the trigger is working. In my console it's showing that the function starts, the console statement is logged, and execution finishes in 40-90ms. But my database is never changed. The deletion statement never appears.

Any help is greatly appreciated!

The documentation explains that a function that performs asynchronous processing must return a JavaScript Promise :

Resolve functions that perform asynchronous processing by returning a JavaScript promise

Change your code to this:

exports.daily_job = functions.pubsub.topic('daily-tick').onPublish((event) => {
  console.log("This job is run every day!");
  const databaseRef = admin.database().ref('/accountActions/dailyDeletion');
  return databaseRef.child('delete').set("Data has been deleted!").then(() => {
    console.log('End of database clearing');
  }).catch(error => {
    console.error('Database clearing failed: ', error);
  });
});

在exports.daily_job。之前的某个位置插入此命令。

admin.initializeApp(functions.config().firebase);

I found the answer to the problem. I had initialized the app according to Firebase's documentation on push notifications:

admin.initializeApp({


  credential: admin.credential.cert({
    projectId: {projectId},
    clientEmail: {email},
    privateKey: {private key}
  }),
 databaseURL: {databaseURL}
 });

But for some reason this caused issues. I switched it out with a simple

admin.initializeApp(functions.config().firebase);

This seems to have fixed the issue, and push notifications are still working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM