如何在Firebase数据库数据更改中使用CloudFunction发送Firebase通知?

时间:2018-10-26 10:23:31

标签: android firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

如果Firebase数据库值被更改,我正在尝试创建云函数,然后发送Firebase通知?下面是我的Firebase数据库快照...就像我要发送liveurl更改通知一样

livestream
    |_ 
      liveurl: "https://www.youtube.com/watch?v=Z8agqyGIaD8"

2 个答案:

答案 0 :(得分:2)

这是Cloud Functions和Cloud Messaging用例的主要示例。实际上,What can I do with Cloud Functions?部分下的Notify users when something interesting happens文档涵盖了类似的情况:

  

notify example

     
      
  1. 该函数触发对存储跟随者的实时数据库路径的写操作。
  2.   
  3. 该函数编写一条消息,以通过FCM发送。
  4.   
  5. FCM将通知消息发送到用户的设备。
  6.   

还有一个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. Deploy this function to Cloud Functions
  2. Setup Cloud Messaging in your app
  3. Subscribe the client app to the liveurl_changed topic

答案 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;
    });

});

});