【发布时间】:2019-03-18 11:08:50
【问题描述】:
我在使用云函数的 admin.database() 检索保存在实时数据库中的令牌时遇到问题。只有一个令牌可以从孩子那里读取。
Firebase 数据库结构
这是我在 Index.js 中的代码
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database
.ref('/Logs/{LogsID}')
.onWrite( (change, context) => {
const notificationSnapshot = change.after.val();
const status = notificationSnapshot.Status;
const time = notificationSnapshot.Time;
const payload = {
notification: {
title : status,
body : time
}
}
console.info(notificationSnapshot);
const pushToken = admin.database().ref('/Tokens').once('child_added').then( (data) => {
const tokenSnapshot = data.val();
const finaltoken = tokenSnapshot.token;
console.info(finaltoken);
})
// Need help down here.
admin.messaging().sendToDevice(finaltoken, payload)
.then( () => {
console.log('Notification sent');
})
.catch( () =>{
console.log('Notification failed');
})
return null;
});
finalToken 按预期在日志中显示正确的令牌。 Log Showing the token
但是当我将相同的令牌传递给 admin.messaging() 时出现错误。控制台正在记录“已发送通知”但未收到通知。
ReferenceError: finaltoken 未定义 在exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:43:36) 在 cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23) 在 cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20) 在 /var/tmp/worker/worker.js:827:24 在 process._tickDomainCallback (internal/process/next_tick.js:135:7)
当我直接传递令牌时它可以工作,
var finalToken = 'ephrj1........kndji'
所以 admin.messaging() 工作,只传递令牌是行不通的。
我是 Cloud Functions 和 javascript 的新手,非常感谢任何帮助。
【问题讨论】:
标签: firebase firebase-realtime-database google-cloud-functions