I am writing a simple app, where I need to send push notifications. For instance, a user liked a post -> send a push notification; or a user commented under a post -> send a push notification; or a user sent you a message -> send a push notification.
I am using Notifications
from expo-notifications
. I have set up my Notifications.addNotificationReceivedListener
and Notifications.addNotificationResponseReceivedListener
. I tested them using Expo's push notification tool and it all works fine.
However, I am struggling to send notifications. As suggested per expo's docs they have a library for Node.js
called expo-server-sdk-node which takes care of sending notifications. As per their doc:
The Expo push notification service accepts batches of notifications so that you don't need to send 1000 requests to send 1000 notifications. We recommend you batch your notifications to reduce the number of requests and to compress them (notifications with similar content will get compressed).
And I agree with the above statement. Sending notifications on batch makes sense, however, I have a question regarding this:
- How do I implement it? Do I keep counter on the user's notification, and lets say, the user has liked 10 posts -> then I send 10 notifications as a batch request? What if they liked 8 posts and then closed the app? Do I send the notifications on closing the app? It doesn't seem right to me. Also, if the user has sent a message, I believe I should straight away send the notification, rather than waiting for a batch request for the user to send 10 messages.
The implementation they offer on their docs is the following:
// Create the messages that you want to send to clients
let messages = [];
for (let pushToken of somePushTokens) {
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
}
// Construct a message (see https://docs.expo.io/push-notifications/sending-notifications/)
messages.push({
to: pushToken,
sound: 'default',
body: 'This is a test notification',
data: { withSome: 'data' },
})
}
Which is OK and understandable. But then I struggle with the next step:
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
(async () => {
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
console.log(ticketChunk);
tickets.push(...ticketChunk);
} catch (error) {
console.error(error);
}
}
})();
That is, at which point do I call expo.chunkPushNotifications(messages)
and then await expo.sendPushNotificationsAsync(chunk)
. Do I wait 10 similar notifications to be collected, do I wait some time, do I do it when the user closes the app, or something else?