notifications chnages

master^2
Bhaskar 9 months ago
parent e35296c0a3
commit d5426f9586

@ -1714,40 +1714,63 @@ const emitWithTimestamp = (eventName, fcmTokens, motorId, waterLevel) => {
// }
// };
const sendNotification = async (fcmTokens, title, body) => {
if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) {
console.error('No FCM tokens provided.');
return;
const sendNotification = async (fcmIds, title, body) => {
try {
if (!fcmIds || fcmIds.length === 0) {
throw new Error('No FCM tokens provided.');
}
// Flatten the nested array of FCM tokens
const flatTokens = fcmIds.flat();
if (flatTokens.length === 0) {
throw new Error('Flattened FCM token list is empty.');
}
const message = {
tokens: fcmTokens, // Send to multiple tokens
notification: {
title: title,
body: body,
title,
body,
},
data: {
target: 'tank_levels', // Any additional data you want to send
exampleKey: 'exampleValue', // Optional additional data
},
};
try {
const response = await admin.messaging().sendMulticast(message); // Send all messages at once
console.log('Notification sent successfully:', response);
// Check for failures
if (flatTokens.length === 1) {
// Single token case
const response = await admin.messaging().send({
...message,
token: flatTokens[0],
});
console.log('Notification sent successfully to single token:', response);
} else {
// Multiple tokens case
const response = await admin.messaging().sendMulticast({
...message,
tokens: flatTokens,
});
console.log('Notifications sent successfully:', response);
// Handle failures
if (response.failureCount > 0) {
response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.error(`Failed to send notification to token ${fcmTokens[idx]}:`, resp.error);
console.error(`Failed to send notification to token ${flatTokens[idx]}:`, resp.error);
}
});
}
}
} catch (error) {
console.error('Error sending notifications:', error);
}
};
// const sendPushNotification = async (registrationToken, title, body) => {
// const message = {
// notification: {
@ -2095,7 +2118,7 @@ exports.motorAction = async (req, reply) => {
// Get user FCM tokens
const users = await User.find({ customerId });
const fcmToken = users.map(user => user.fcmIds).filter(fcmIds => fcmIds);
console.log(fcmToken)
const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
console.log(receiverTank)
const currentWaterLevel = parseInt(receiverTank.waterlevel, 10);

Loading…
Cancel
Save