I have a cron job function running on Firebase functions, which fetches all documents from my User collection in Firestore, and sends notification using FCM to their devices. Due to limitations on how many tokens you can send to in one go, I'm splitting all my users tokens up in chunks of 100, and sending it in batches.
const admin = require("firebase-admin");
const fcm = admin.messaging();
const _ = require("lodash");
....
const deviceTokens = [.....] // <- flat array with all device tokens
const chunkedList = _.chunk(deviceTokens, 100); // [[...], [...], ...]
const message = "some message";
const sendAll = async () => {
const sendInChunks = chunkedList.map(async (tokenArr) => {
await fcm.sendToDevice(tokenArr, message);
});
await Promise.all(sendInChunks);
};
await sendAll();
I'm trying to understand from the documentation if this would be a safe way of doing it. For example, if one of the device tokens is stale or for some other reason fails, will that whole call to fcm.sendToDevice
fail with along with the other tokens that was passed in, or will just that single device not recieve it? Or is there anything else I'm missing here?
CodePudding user response:
Having one or more invalid/outdated tokens in the API call does not cause that call to fail.
Instead the FCM API (and its Admin SDK wrappers) will try to deliver each message separately and report back which specific tokens that you passed are unknown/outdated. You'll want to process those results and use them to prune your own token registry, similar to what this code sample in our Cloud Functions samples repro shows.