Lukayne
Lukayne

Reputation: 43

How to increment badge count with firebase cloud functions

Right now my payload only sends 1 badge count, the value of the badge count does not increment. It remains as 1, even if you get more than 1 notifications.

How should the javascript be written?

My current code:

const functions = require('firebase-functions');                   
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase);
exports.sendPushForHelp = 
functions.database.ref('/help/school/{id}').onWrite(event => {
   const payLoad = {
     notification: {
         title: 'Someone',
         body: 'needs help',
         badge: '1',
         sound: 'Intruder.mp3'
     }
   };
   return admin.database().ref('fcmToken').once('value').then(allToken => {
       if (allToken.val()) {
        const token = Object.keys(allToken.val());
        return admin.messaging().sendToDevice(token, payLoad).then(response => {

            });
        };
    });
});

Upvotes: 4

Views: 3883

Answers (1)

Surreal
Surreal

Reputation: 1047

You can store a badgeCount in your JS and have it increment on every call, or randomize it or what have you

ie:

const functions = require('firebase-functions');                   
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase);
var badgeCount = 1;
exports.sendPushForHelp = 
functions.database.ref('/help/school/{id}').onWrite(event => {
   const payLoad = {
     notification: {
         title: 'Someone',
         body: 'needs help',
         badge: badgeCount.toString(),
         sound: 'Intruder.mp3'
     }
   };
   badgeCount++; //or whatever
   return admin.database().ref('fcmToken').once('value').then(allToken => {
       if (allToken.val()) {
        const token = Object.keys(allToken.val());
        return admin.messaging().sendToDevice(token, payLoad).then(response => {
          //here might be a good place to increment as well, only on success
            });
        };
    });
});

Upvotes: 4

Related Questions