3

I am using Firebase as my back end for my Android app and am very new to using Cloud Functions for Firebase and I was wondering how I would send specific users push notification when an event occurs.

For example how would I send the user with uId in the below code a push notification when a write occurs at adminName node on the database:

exports.sendNotification = functions.database.ref('/users/{uId}/groups/{adminName}')
    .onWrite(event => {

    // Grab the current value of what was written to the Realtime Database.
    var eventSnapshot = event.data;
    var str1 = "Author is ";
    var str = str1.concat(eventSnapshot.child("author").val());
    console.log(str);

    var topic = "android";
    var payload = {
        data: {
            title: eventSnapshot.child("title").val(),
            author: eventSnapshot.child("author").val()
        }
    };

    // Send a message to devices subscribed to the provided topic.
    return admin.messaging().sendToTopic(topic, payload)
        .then(function (response) {
            // See the MessagingTopicResponse reference documentation for the
            // contents of response.
            console.log("Successfully sent message:", response);
        })
        .catch(function (error) {
            console.log("Error sending message:", error);
        });
    });
1
  • You have to have the registration token for that specific user and use sendToDevice. Commented May 10, 2017 at 2:49

1 Answer 1

1

Make the below changes. it works for me

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().functions);

var newData;

exports.myTrigger = functions.firestore.document('TestCollection/{id}').onWrite(async (snapshot, context) => {
//

if (snapshot.empty) {
    console.log('No Devices');
    return;
}

newData = snapshot.data();

const deviceIdTokens = await admin
    .firestore()
    .collection('DeviceIDTokens')
    .get();

var tokens = [];

for (var token of deviceIdTokens.docs) {
    tokens.push(token.data().device_token);
}
var payload = {
    notification: {
        title: 'Push Title',
        body: 'Push Body',
        sound: 'default',
    },
    data: {
        push_key: 'Push Key Value',
        key1: newData.data,
    },
};

try {
    const response = await admin.messaging().sendToDevice(tokens, payload);
    console.log('Notification sent successfully');
} catch (err) {
    console.log(err);
}
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.