firebase - 当存储在firestore数据库中的日期是今天的日期时如何触发功能?
问题描述
我正在创建一个应用程序,当今天的日期与数据库中存储的日期匹配时,我需要发送推送通知以发送推送通知。如何做到这一点?
解决方案
更新:
您可以使用预定的云函数,而不是编写通过在线 CRON 作业服务调用的 HTTPS 云函数。Cloud Function 代码保持不变,只是触发器发生了变化。
在编写初始答案时,计划的云功能不可用。
在不了解您的数据模型的情况下,很难给出准确的答案,但让我们想象一下,为了简化,您在每个文档中存储了一个名为notifDate
DDMMYYY 格式的字段,并且这些文档存储在一个名为 的集合中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()
并行执行多个异步任务(方法)。这在上面提到的第三个视频中有详细说明。
推荐阅读
- java - wifiManager.getScanResult() 返回空值
- r - 重新安装keras。Win10上R中的张量流
- javascript - 在 javascript 中使用 fetch 请求 API 存在 CORS 策略错误
- here-api - 特定 bbox 中列出的地点数
- javascript - Object.fromEntries 仅在 iOS 上可用?(反应原生 - 不是 WEB)
- java - 我想单击第三个窗口上的按钮,这是一个活动元素
- cybersource - 在 CyberSource 中,您如何将信用卡灵活令牌与支付 API 结合使用?
- html - 如何在我的 html 代码中输入一些音乐?
- datatables - 如何从此表创建堆积条形图
- java - 如何在启动时将数据写入文件