Peter Sypek
Peter Sypek

Reputation: 153

Cloud Functions for Firebase send push to multiple users

I try to get multiple push notifications to run on Cloud Functions for Firebase without success.

I store my message receipts in a node

To send push notifications I try following on cloud functions:

//*********************************************************************************************************** */
//handle lsit item added by shared user
if (String(msgData.messageType) == 'ListItemAddedBySharedUser') {

    return admin.database().ref("message_receipts").child(event.params.messageID).once('value').then(receipts => {

        receipts.forEach(function (receipt) {

            //Send push to receipt
            return admin.database().ref('/users/' + receipt.key).once('value').then(usnap => {

                //Send push to users fcmToken
                const userSnap = usnap.val()
                console.log('sending Push to ' + userSnap.fcmToken)


                //create Notification Payload
                var payload = {
                    notification: {
                        title: msgData.title,
                        body: msgData.message,
                        badge: '1',
                        sound: 'default',
                        sbID: String(event.data.key),
                        senderID: msgData.senderID,
                        listID: msgData.listID,
                        receiptID: receipt.key,
                        notificationType: String(msgData.messageType),
                    }
                };

                return admin.messaging().sendToDevice(userSnap.fcmToken, payload).then(response => {

                    console.log("Successfully sent invite message:", response)
                    console.log(response.results[0].error)

                }).catch((err) => { console.log("Error sending Push", err) })

            })

        })

    })
} //*********************************************************************************************************** */

All I get is one notification sent. I'am very new to java script and cloud functions. What do I need to do to get all of my users notified?

Upvotes: 1

Views: 1368

Answers (2)

Mutlu Simsek
Mutlu Simsek

Reputation: 1172

You can send a batch of messages as described in the documentation:

https://firebase.google.com/docs/cloud-messaging/send-message#send-a-batch-of-messages

// Create a list containing up to 500 messages.
const messages = [];
messages.push({
  notification: {title: 'Price drop', body: '5% off all electronics'},
  token: registrationToken,
});
messages.push({
  notification: {title: 'Price drop', body: '2% off all books'},
  topic: 'readers-club',
});

return admin.messaging().sendAll(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

Upvotes: 0

Michael Bleigh
Michael Bleigh

Reputation: 26353

You need to aggregate all of the asynchronous actions you're taking. Here you're doing a forEach on the message receipts, but then you're returning a single promise. Try something like:

var promises = [];
receipts.forEach(function (receipt) {
    //Send push to receipt
    promises.push(admin.database().ref('/users/' + receipt.key).once('value').then(usnap => {
        /* ... */
    }))
})

return Promise.all(promises);

This will aggregate all of your outstanding notifications into a single Promise.all call, which will wait until they all complete.

Upvotes: 1

Related Questions