我使用 firebase 函数来触发推送通知。
我可以发送通知,但在触发器启动时无法读取某些数据。
我尝试了常用的 Firebase 数据库功能,但它们不起作用。
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
let fcm = ''
exports.sendNewMessageNotification = functions.database.ref('/xxx/userInformations/{uid}/')
.onWrite((change:any) => {
// console.log(change.before)
const payload = {
notification: {
title: 'Kahve Falı',
body: 'Falın geldi!',
}
}
admin.database().ref('/xxx/userInformations/{uid}/fortunes')
.once('value')
.then((snapshot:any) => {
console.log('snapshot.val()')//I want to get that snaphot.val()
});
fcm = change.before._data.fcm;
return admin.messaging().sendToDevice(fcm, payload);
});
它不会读取该快照。它以不同的方式返回 null 或 undefined。
我不能那样做这条线;
.then((快照) => {
如果我不输入 :any
,则会在 VS Code 上出现错误。
最佳答案
您似乎弄错了代码的两部分。
<小时/>首先你有:
exports.sendNewMessageNotification = functions.database.ref('/xxx/userInformations/${uid}/')
这声明了一个云函数。当您使用 Firebase 部署此代码时,它会识别此 Cloud Function 并将字符串文字 '/xxx/userInformations/${uid}/'
解释为此代码需要触发的路径。它将路径中 /xxx/userInformations
之后的值放入名为 uid
的参数中。
接下来你有:
admin.database().ref('/xxx/userInformations/${uid}/fortunes')
这是常规 JavaScript 代码,在这种情况下,'/xxx/userInformations/${uid}/fortunes'
只是发送到 Firebase 客户端的字符串。由于路径中不允许使用 $
,Firebase 客户端会引发错误。
您可能希望路径包含 uid
参数的值,您可以使用以下方法:
admin.database().ref(`/xxx/userInformations/${context.params.uid}/fortunes`)
所以变化:
- 使用反引号标记字符串,以便将其解释为 ES6 Template Literal .
- 在其中使用
${context.params.uid}
来获取用于触发代码的uid
值。
这要求您在 Cloud Function 声明中定义上下文
,例如:
.onWrite((change:any, context: any) => {
关于node.js - 我无法读取 Firebase Functions 上的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746246/