我希望每次从firebase数据库中修改聊天时,都会激活此功能“ sendNotification”,但是会出现此错误:
sendNotification
ReferenceError: receiverId is not defined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:11:29)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:730:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
我有这个JavaScript代码,但我不知道为什么它告诉我没有定义receiveId,非常感谢。
let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/Chat/{userId}/{messageId}').onWrite((change, context) => {
//get the userId of the person receiving the notification because we need to get their token
const receiverId = context.params.userId;
console.log("receiverId: ", receiverId);
//get the user id of the person who sent the message
const senderId = context.data.child('user_id').val();
console.log("senderId: ", senderId);
//get the message
const message = context.data.child('message').val();
console.log("message: ", message);
//get the message id. We'll be sending this in the payload
const messageId = context.params.messageId;
console.log("messageId: ", messageId);
//query the users node and get the name of the user who sent the message
return admin.database().ref("/users/" + senderId).once('value').then(snap => {
const senderName = snap.child("name").val();
console.log("senderName: ", senderName);
//get the token of the user receiving the message
return admin.database().ref("/users/" + receiverId).once('value').then(snap => {
const token = snap.child("messaging_token").val();
console.log("token: ", token);
//we have everything we need
//Build the message payload and send the message
console.log("Construction the notification message.");
const payload = {
data: {
data_type: "direct_message",
title: "New Message from " + senderName,
message: message,
message_id: messageId,
}
};
return admin.messaging().sendToDevice(token, payload)
.then(function(response) {
return console.log("Successfully sent message:", response);
})
.catch(function(error) {
return console.log("Error sending message:", error);
});
});
});
});
答案 0 :(得分:0)
显然您正在使用Firebase SDK for Cloud Functions的旧版本,该版本为<到1.0版本,但是语法(onWrite((change, context))
)对应于> = 1.0版本。
该图像显示onWrite.event上的错误,该错误与旧语法(.onWrite((event))
)相对应。
您应按以下步骤更新项目中的SDK:
npm install firebase-functions@latest --save npm install firebase-admin@latest --save-exact
您还应该将Firebase CLI更新到最新版本:
npm install -g firebase-tools
有关所有详细信息,请参见此文档item。