is there any way to send different badge count to different users in a same topic?

Viewed 2297

I have FCM integration in my Node.js project where I am sending number of notifications to the IOS users and I need to manage notification count i.e. Badge count which will be different across the devices but I am sending notification to a particular topic to which these devices are subscribed.

my Payload is :

    var payload = {
            notification: {
                title: "Title...",
                body: "Notification Body...",
                sound: "customeSound.caf",
                badge : "?"
            },
            data: {
                testData: "custom data"
            }
        },
topic = "topicName";

        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);
            });
    });
2 Answers

If you have the devices tokens and you want to send the badge counts to respective device token,

Instead of sending them one by one ( Which I personally think is not a good idea) the best alternative you can do is:-

You can achieve this by doing something like..... First of all you need to query your DB to get the device token and badge count respectively

So say like you have and array

const badgeCounts = [{
    device_token:'aaaaaaaaaaaaaaaaaaaaaa',
    badge_count: 1
},{
    device_token:'bbbbbbbbbbbbbbbbbbbbbb',
    badge_count: 2
},{
    device_token:'cccccccccccccccccccccc',
    badge_count: 3
},{
    device_token:'dddddddddddddddddddddd',
    badge_count: 4
}]

Now you can map over this array and compose array of fcm messages, something like below :-

const fcmMessages = [];

badgeCounts.forEach((data) => {
  fcmMessages.push({
    token: data.device_token, //device token
    apns: {
      payload: {
        aps: {
          alert: {
            title: "your title",
            body: "your body",
          },
          badge: data.badge_count, // badge
          contentAvailable: true,
        },
      },
    },
    data: {
      // any payload goes here...
    },
    notification: {
      title: "your title",
      body: "your body",
    },
  });
});

/// in firebase messiging you can do like
messaging.sendAll(fcmMessages);

refer doc https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging-1#sendall

Related