Firebase Cloud Function Error: Registration Token(s) Provided To SendToDevice() Must Be A Non-empty String Or A Non-empty Array
I want to send a notification to all users who are confirmed guests when the object confirmedGuests is created in the Firebase Realtime Database. So, I first create an array of al
Solution 1:
You're loading each user's device tokens from the realtime database with:
admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
This load operation happens asynchronously. This means that by the time the admin.messaging().sendToDevice(allDeviceTokens, payload)
calls runs, the tokens haven't been loaded yet.
To fix this you'll need to wait until all tokens have loaded, before calling sendToDevice()
. The common approach for this is to use Promise.all()
let promises = [];
for(let i=0; i<guestIds.length; i++){
let userId = guestIds[i]
let promise = admin.database().ref(`/users/${userId}/deviceTokens`).once('value', (tokenSnapshot) => {
let userData = tokenSnapshot.val();
let userItem = Object.keys(userData).map(function(key) {
return userData[key];
});
userItem.map(item => allDeviceTokens.push(item))
return true;
})
promises.push(promise);
}
return Promise.all(promises).then(() => {
return admin.messaging().sendToDevice(allDeviceTokens, payload);
})
Post a Comment for "Firebase Cloud Function Error: Registration Token(s) Provided To SendToDevice() Must Be A Non-empty String Or A Non-empty Array"