Skip to content

Instantly share code, notes, and snippets.

@vunguyentuan
Created December 28, 2021 15:07
Show Gist options
  • Save vunguyentuan/fdb00560eda73de6d88fd4e1b9fb5ebd to your computer and use it in GitHub Desktop.
Save vunguyentuan/fdb00560eda73de6d88fd4e1b9fb5ebd to your computer and use it in GitHub Desktop.
Firebase batch send notification
export const sendNotifications = functions
.runWith({
timeoutSeconds: 540,
memory: '1GB',
})
.https.onRequest(async (req, res): Promise<void> => {
const { fromIndex, toIndex } = req.body;
const usersDataResponse = await db.users.orderBy('userIndex').startAt(fromIndex).endAt(toIndex).get();
const userToSendNotifications = usersDataResponse.docs.filter(onlyUserAtTimezone)
try {
await PromisePool.for(userToSendNotifications)
.withConcurrency(100)
.process(async (user) => {
try {
const userData = user.data();
const tokens = userData.tokens || [];
const notificationData = prepareNotification(userData);
if (notificationData && tokens.length > 0) {
const response = await messaging().sendMulticast({
tokens: tokens,
notification: notificationData,
});
if (response.failureCount > 0) {
const failedTokens: string[] = [];
response.responses.forEach((resp, idx) => {
// Cleanup the tokens who are not registered anymore.
if (
resp.error?.code === 'messaging/invalid-registration-token' ||
resp.error?.code === 'messaging/registration-token-not-registered'
) {
failedTokens.push(tokens[idx]);
}
});
// remove failed tokens
if (failedTokens.length > 0) {
await db.users.doc(user.id).update({
tokens: firestore.FieldValue.arrayRemove(...failedTokens),
});
}
console.log('List of tokens that caused failures: ' + failedTokens);
}
}
} catch (error) {
functions.logger.error('error', error);
}
});
res.send('OK');
} catch (error) {
res.sendStatus(500);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment