Skip to content Skip to sidebar Skip to footer

How Can I Send Firebase Notifications Using Cloudfunctions On Firebase Database Datachange?

I'm trying to create a cloud function if firebase database value is changed and then I send a firebase notification? below is my firebase database snapshot...it's like I want to se

Solution 1:

This is a prime example of a use case for Cloud Functions and Cloud Messaging. In fact, a similar scenario is covered in the What can I do with Cloud Functions? documentation under the Notify users when something interesting happens section:

notify example

  1. The function triggers on writes to the Realtime Database path where followers are stored.
  2. The function composes a message to send via FCM.
  3. FCM sends the notification message to the user's device.

There is also a FCM Notifications quickstart sample available on GitHub for this.

As a quick example, you could write a Cloud Function to do this, something like:

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()) returnnull;

    // 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);
        });
});

This is a Cloud Functions method that will react to changes to the /livestream/liveurl node in your database and use Cloud Messaging to send a message to a topic (namely liveurl_changed).

In order for this to work, you'll need to:

  1. Deploy this function to Cloud Functions
  2. Setup Cloud Messaging in your app
  3. Subscribe the client app to the liveurl_changed topic

Solution 2:

Try this cloud function :

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 userreturn 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);
        return0;
    });

});

});

Post a Comment for "How Can I Send Firebase Notifications Using Cloudfunctions On Firebase Database Datachange?"