所以这是错误;
类型错误: 无法读取未定义的属性 'val' at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:14:19( 在对象。(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27( 在下一个(本地( at/user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12( at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36( at/var/tmp/worker/worker.js:728:24 在process._tickDomainCallback(内部/进程/next_tick.js:135:7(
这是我的代码:
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification = context.params.notification;
console.log('We have a notification to send to : ', user_id);
if(!context.data.val()){
return console.log('A notification has been deleted from the database:', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title : "Friend Request",
body : "You've receieved a new Friend Request",
icon : "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This is the notification Feature');
});
});
});
而不是context.data.val()
使用change.after.exists()
请测试此函数:
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification = context.params.notification_id;
console.log('We have a notification to send to : ', user_id);
if (!change.after.exists()) {
console.log('A notification has been deleted from the database:', notification);
return null;
}
const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: "Friend Request",
body: "You've receieved a new Friend Request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This is the notification Feature');
});
});
});
而不是
const token_id = result.val();
尝试
const token_id = result.after.data();