Write to firebase database from cloud function triggered by PubSub

蓝咒 提交于 2021-01-28 09:44:23

问题


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!


回答1:


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.




回答2:


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);
  });
});



回答3:


Insert this command somewhere before exports.daily_job..

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


来源:https://stackoverflow.com/questions/46473933/write-to-firebase-database-from-cloud-function-triggered-by-pubsub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!