【发布时间】:2021-06-06 22:42:18
【问题描述】:
当 Firestore 数据字段发生更改时,是否可以通过 Firebase Cloud Functions 发送 FCM 通知,但对于网站,而不是应用程序。除了从 Firebase 控制台发送通知外,还有很多针对 Android 和 iOS 的指导,但对于简单的 Web 应用没有任何指导)。
我一直在尝试找出如何从 Cloud Functions 触发通知,但找不到任何有用的东西。
例如,我的数据库结构如下:
- 集合:用户
- 文档:使用用户 ID 命名的文档
- 数据字段:字段 1 到 5。字段 5 存储 FCM 令牌。字段 1 存储其状态(在线、离线、离线待处理消息)。
我想确保当数据字段 1 发生更改(变为“离线待处理消息”)时,相关用户会收到通知(基于文档 ID)。
编辑:在下面添加代码以供参考
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/users/{doc}/{Hears}')
.onUpdate(async (change, context) => {
const db = admin.firestore();
db.collection('users').doc(context.params.userId) // get userId
.get()
.then(doc => {
//this is intended to get the FCM token stored in the user's document
const fcmToken = doc.data().usrTkn;
// Notification details
const payload = {
notification: {
title: 'You have a new message.',
body: 'Open your app'
}
};
})
//This should send a notification to the user's device when web app is not in focus.
//FCM is set up in service worker
const response = await admin.messaging().sendToDevice(fcmToken, payload);
console.log(response);
});
【问题讨论】:
标签: javascript google-cloud-firestore google-cloud-functions firebase-cloud-messaging