firebase - 从 Cloud Function 返回 null 的 Firebase 快照值
问题描述
*图片删除
这是我的 firebase 数据库,我正在尝试从数据库中的更改或添加等事件设置远程推送消息。
我进行了设置,以便多个设备可以共享同一个帐户,并且每个设备将设备令牌写入一个子设备,并将 FCM 令牌存储为该子设备下的密钥。
所以这里看到的关键值是 [FCMtoken : true]
我对如何使用 Javascript 感到困惑,这是我返回空值的函数,尽管我希望它返回设备 FCMtoken。
exports.notificationForCommunicationAdded = functions.database.ref('/{pharmacyId}/orders/{orderId}/communications')
.onWrite(event => {
const payload = {
notification: {
title: 'New communication added',
body: 'Check it out!'
}
};
const getDeviceTokensPromise = admin.database().ref('/{pharmacyId}/userDevices/{deviceToken}').once('value');
let tokensSnapshot;
let tokens;
return getDeviceTokensPromise.then(results => {
tokensSnapshot = results;
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send to');
tokens = Object.keys(tokensSnapshot.val());
console.log('These are the tokens', tokens)
return null;
});
});
尽我所能尝试我不断将“null”作为我的返回值。
帮助将不胜感激,谢谢伙计们。
解决方案
当您访问数据库时,您不能像这样进行变量替换:
admin.database().ref('/{pharmacyId}/userDevices/{deviceToken}')
那些花括号是按字面意思理解的。它们不像函数定义中的通配符那样工作。您需要使用未声明的上下文参数使用通配符的值构建一个字符串。首先,您需要像这样声明您的函数:
exports.notificationForCommunicationAdded =
functions.database.ref('/{pharmacyId}/orders/{orderId}/communications')
.onWrite((change, context) => {
请注意,第一个对象是 Change 对象,第二个是上下文。
然后您需要使用上下文来获取通配符值:
const pharmacyId = context.params.pharmacyId
const orderId = context.params.orderId
然后你需要使用这些来构建数据库的路径:
admin.database().ref(`/${pharmacyId}/userDevices/${deviceToken}`)