I'm invoking the method sendToDevice of Firebase Cloud Messaging (FCM) in Cloud Function (Node Js).
I pass the token parameters with multiple tokens such as [token1, token2, ... ]
Then I received a response of type MessagingDevicesResponse.
The code is like this:
//Array of Strings. token1-3 are strings
const tokens = [token1, token2, token3];
await admin
.messaging()
.sendToDevice(tokens, payload)
.then((response) => { // response is type MessagingDevicesResponse
for (let i = 0; i < response.results.length; i++) {
const res = response.results[i];
if(res.error) {
//* If error found on index i
//*** Do something to delete the non-registered token
}
}
return { success: true };
})
.catch((error) => {
console.error(
`Error while sending notification. Code: ${error.code}, Error: ${error}`);
return { error: error };
});
Now, as you can see that tokens variable is an array of strings.
Consequently, response.results also return the same length as tokens.
But the question is, does the indexes in response.results maps to the same index as tokens?
I mean, does response.results[0] means it is the result for sending notification to the device with the token in tokens[0], and so on?
Thank you
Yes, the elements in the response.results Array are listed in the same order as in the tokens Array.
This was previously documented and apparently it has been removed. See the last comment of this GitHub Issue thread.
Look also at this Cloud Function sample, which does exactly what you are looking for (i.e. deleting the non-registered tokens)
Better validate all the registration tokens and then delete the invalid ones, before sending already. One can post chunks of 500 registration tokens each and the "unknown" ones (if any) are not really "invalid", but do belong to another project. Generally speaking, this needs some house-keeping, eg. just recently wiped out 27.5% of registration tokens, because they weren't valid anymore.