这是index.js,
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
console.log('Push notification event triggered');
const message = event.data.val();
const user = event.data.val();
console.log(message);
console.log(user);
const topic = "myTopic";
const payload = {
"data": {
"title": "New Message from " + user,
"detail":message,
}
};
return admin.messaging().sendToTopic(topic, payload);
});
上面的代码配置错误,当我在Node.js中部署时,LOG中的函数显示:
“TypeError:无法读取未定义的属性'val'。
实际上我正在尝试做什么: 我正在尝试将快照加载中的信息提取到index.js中,以便在将新子项添加到实时数据库时,它应该触发带有标题和正文的通知负载。
在Android中,我使用子监听器,在添加新记录时进行监听
FirebaseDatabase.getInstance().getReference().child("messages")
OnChildAdded(.....){
if (dataSnapshot != null) {
MessageModel messageModel = dataSnapshot.getValue(MessageModel.class);
if (messageModel != null) {
// do whatever
}
}
但是在index.js中,我无法解析它。 根据我的数据库结构如何固定index.js的一点指导将非常感激。 PS-我从未在JS中编码 如果你想要更多的背景,我很乐意提供它。
答案 0 :(得分:33)
改变这个:
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
const message = event.data.val();
const user = event.data.val();
});
到此:
exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {
const message = change.after.val();
});
请检查:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
云功能已更改,现在onWrite
有两个参数change
和context
change
有两个属性before
和after
,其中每个属性都是DataSnapshot
,其中列出的方法如下:
https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot
答案 1 :(得分:-1)
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/NOTIFICATIONS/{UserId}/{{notification_id}').onWrite((change, context) =>
{
const UserId = context.params.UserId;
const notification = context.params.notification;
console.log('The user Id is : ', UserId);
if(!change.after.exists())
{
return console.log('A Notification has been deleted from the database : ', notification_id);
}
if (!change.after.exists())
{
return console.log('A notification has been deleted from the database:', notification);
return null;
}
const deviceToken = admin.database().ref(`/USER/${UserId}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload = {
notification : {
title : "Friend Request",
body : "You've received a new Friend Request",
icon : "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});