首页 > 解决方案 > 当存储在firestore数据库中的日期是今天的日期时如何触发功能?

问题描述

我正在创建一个应用程序,当今天的日期与数据库中存储的日期匹配时,我需要发送推送通知以发送推送通知。如何做到这一点?

标签: firebasereact-nativegoogle-cloud-firestoregoogle-cloud-functionsonesignal

解决方案


更新:

您可以使用预定的云函数,而不是编写通过在线 CRON 作业服务调用的 HTTPS 云函数。Cloud Function 代码保持不变,只是触发器发生了变化。

在编写初始答案时,计划的云功能不可用。


在不了解您的数据模型的情况下,很难给出准确的答案,但让我们想象一下,为了简化,您在每个文档中存储了一个名为notifDateDDMMYYY 格式的字段,并且这些文档存储在一个名为 的集合中notificationTriggers

您可以编写一个 HTTPS 云函数,如下所示:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const cors = require('cors')({ origin: true });
const moment = require('moment');

admin.initializeApp();

exports.sendDailyNotifications = functions.https.onRequest((request, response) => {

    cors(request, response, () => {
  
       const now = moment();
       const dateFormatted = now.format('DDMMYYYY');

       admin.firestore()
       .collection("notificationTriggers").where("notifDate", "==", dateFormatted)
       .get()
       .then(function(querySnapshot) {

           const promises = []; 

           querySnapshot.forEach(doc => {
 
               const tokenId = doc.data().tokenId;  //Assumption: the tokenId is in the doc
               const notificationContent = {
                 notification: {
                    title: "...",
                    body: "...",  //maybe use some data from the doc, e.g  doc.data().notificationContent
                    icon: "default",
                    sound : "default"
                 }
              };

              promises
              .push(admin.messaging().sendToDevice(tokenId, notificationContent));      
  
          });
          return Promise.all(promises);
       })
       .then(results => {
            response.send(data)
       })
       .catch(error => {
          console.log(error)
          response.status(500).send(error)
       });

    });

});

然后,您每天都会使用在线 CRON 作业服务(如https://cron-job.org/en/ )调用此 Cloud Functions 。

有关如何在 Cloud Functions 中发送通知的更多示例,请查看那些 SO 答案 Send push notification using cloud function when a new node is added in firebase realtime database? , node.js firebase deploy 错误Firebase: Cloud Firestore trigger not working for FCM

如果您不熟悉在 Cloud Functions 中使用 Promises,我建议您观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频:https ://firebase.google.com/docs/functions/video-series/

您会注意到Promise.all()上面代码中的使用,因为您正在sendToDevice()并行执行多个异步任务(方法)。这在上面提到的第三个视频中有详细说明。


推荐阅读