我想在Android上以Lapit Chat的形式建立聊天,我正在编写此node.js脚本并将其部署:
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = change.params.user_id;
const notification_id = change.params.notification_id;
console.log('We have a notification from : ', user_id);
if (!change.after.val()) {
return console.log('A notification has been deleted from database: ', notification_id);
}
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
const payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you request`,
icon: "default",
click_action : "com.example.ragha.safeheartchatting_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notification Feature');
});
});
});
});
运行应用程序并在firebase云上发送请求后,出现错误,它出现在firebase数据库中,但没有出现在移动android上
TypeError:无法读取未定义的属性“ user_id” 在exports.sendNotification.functions.database.ref.onWrite.event(/user_code/index.js:12:31) 在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:768:24 在process._tickDomainCallback(internal / process / next_tick.js:135:7)
答案 0 :(得分:0)
如果要使用通配符的值,请使用context
,而不要使用change
。 change
仅描述触发您的函数调用的数据库更改。
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;