如果Firebase数据库值被更改,我正在尝试创建云函数,然后发送Firebase通知?下面是我的Firebase数据库快照...就像我要发送liveurl更改通知一样
livestream
|_
liveurl: "https://www.youtube.com/watch?v=Z8agqyGIaD8"
答案 0 :(得分:2)
这是Cloud Functions和Cloud Messaging用例的主要示例。实际上,What can I do with Cloud Functions?部分下的Notify users when something interesting happens文档涵盖了类似的情况:
- 该函数触发对存储跟随者的实时数据库路径的写操作。
- 该函数编写一条消息,以通过FCM发送。
- FCM将通知消息发送到用户的设备。
还有一个FCM Notifications quickstart sample available on GitHub。
作为一个简单的示例,您可以编写一个Cloud Function来执行此操作,例如:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.liveUrlChange = functions.database.ref('/livestream/liveurl').onWrite((event) => {
// Exit if data is deleted.
if (!change.after.exists()) return null;
// Grab the current value of what was written to the Realtime Database.
const value = change.after.val();
console.log('The liveurl value is now', value);
// Build the messaging notification, sending to the 'all' topic.
var message = {
notification: {
title: 'Database change',
body: 'The liveurl value has changed to ' + value
},
topic: 'liveurl_changed'
};
// Send the message.
return admin.messaging().send(message)
.then((message) => {
console.log('Successfully sent message:', message);
})
.catch((error) => {
console.error('Error sending message:', error);
});
});
这是一种Cloud Functions方法,将对数据库中对/livestream/liveurl
节点的更改做出反应,并使用Cloud Messaging来send a message to a topic(即liveurl_changed
)。
要使其正常工作,您需要:
答案 1 :(得分:1)
尝试使用此云功能:
exports.sendNotification = functions.database.ref('/livestream/{liveurl}').onUpdate((data, context) => {
const liveurl = context.params.liveurl;
//getting the instance of the target user. this instance object will contain the device token of the target user
return admin.database().ref(`/apps/${app_id}/users/${sender_id}/instances`).once('value').then(function(instancesIdAsObj) {
const tokens = Object.keys(instancesIdAsObj.val());
const payload = {
notification: {
title: sender_fullname,
body: text,
icon : "ic_notification_small",
sound : "default",
click_action: "NEW_MESSAGE",
"content_available": "true",
badge : "1"
},
data: {
liveurlString: liveurl,
}
};
return admin.messaging().sendToDevice(tokens, payload).then(function (response) {
console.log("Push notification for message "+ JSON.stringify(message) + " with payload "+ JSON.stringify(payload) +" sent with response ", JSON.stringify(response));
return error;
}
});
})
.catch(function (error) {
console.log("Error sending message:", error);
return 0;
});
});
});