Created
December 28, 2021 15:07
-
-
Save vunguyentuan/fdb00560eda73de6d88fd4e1b9fb5ebd to your computer and use it in GitHub Desktop.
Firebase batch send notification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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