Reputation: 624
I have a data like this:
notification
|----event01
|---- token : "gdTh21dG705ysFA91..."
|---- timestamp : 1513335600000
|---- name : "Name Event A"
|---- etc
|----event02
|---- token : "dG7058J1L8I:APA91..."
|---- timestamp : 1513335600000
|---- name : "Name Event B"
|---- etc
|----event03
|---- token : "dG7058J1L8I:APA91..."
|---- timestamp : 1513355000000
|---- name : "Name Event C"
|---- etc
I need to send FCM to user with token
when timestamp
has come, there will be more than 1 event with same timestamp
but different name
, so I can't just send the message using array of token.
I try to send the message like this, but if there is more than 1 event with same timestamp, only first message sent, without error.
how I can send all message with one functions, the event with same timestamp can be 2,3,4... or 100.
// Runs Promises in a pool that limits their concurrency.
const promisePool = require('es6-promise-pool');
const PromisePool = promisePool.PromisePool;
// Maximum concurrent message sending.
const MAX_CONCURRENT = 3;
/**
* Send notification to user based on timestamp
* Triggered when /variable/notification node updated
* The node updated by C# service when the event is starting
*/
exports.sendStartNotification = functions.database.ref('/variables/notification').onUpdate(event => {
const epoch = event.data.val();
return admin.database().ref('/notification').orderByChild('timestamp').equalTo(epoch).once('value').then(snapshot => {
// Use a pool so that we send maximum `MAX_CONCURRENT` notification in parallel.
const promisePool = new PromisePool(() => {
snapshot.forEach(childSnapshot => {
let notif = childSnapshot.val();
if (notif.token !== null && notif.token !== undefined && notif.token !== '') {
let payload = {
data: {
key: childSnapshot.key,
title: `Event ${notif.name} started`,
body: `Please check-in`
}
};
// Send the message
return admin.messaging().sendToDevice(notif.token, payload).catch(error => {
console.log("Sending failed:", error);
});
}
});
}, MAX_CONCURRENT);
promisePool.start().then(() => {
console.log(`Sending success ${epoch}`);
});
});
});
Upvotes: 3
Views: 1233
Reputation: 598775
You're not returning a promise at the end of your code, which means it may be terminated at any time (or continue running longer than necessary).
return promisePool.start();
I've never used promise pools, so would definitely consider using a regular Promise.all()
to see if that makes a difference:
var promises = [];
snapshot.forEach(childSnapshot => {
let notif = childSnapshot.val();
if (notif.token !== null && notif.token !== undefined && notif.token !== '') {
let payload = {
data: {
key: childSnapshot.key,
title: `Event ${notif.name} started`,
body: `Please check-in`
}
};
// Send the message
promises.push(admin.messaging().sendToDevice(notif.token, payload));
}
});
return Promise.all(promises);
Upvotes: 1