Reputation: 19514
Is there any way to send a notification to specified users?
const res = await db.collection('users')
.where('businessDetails.serviceSubCategories','array-contains',subId)
.where('businessDetails.isApplied','==','Y')
.get();
if(res.empty){
return;
}else{
//send notification only response users
const payload: admin.messaging.MessagingPayload = {
notification:{
title: `New Enquiry`,
body:`${customerName} published to ${subName}`,
badge: '1',
sound: 'default'
}
}
return fcm.sendToTopic('requirements',payload);
}
Upvotes: 0
Views: 34
Reputation: 145
Firebase has 2 different ways to send FCM messages :
link to FCM documentation The token is generated client-side and that you have to send very securely to the DB (if someone has access to that token he will be able to send notifications to your user).
Here comes the code to send the notification :
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Now begs the question on how to get the token from the user : More informations there
Here is the code for the WEB :
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
Upvotes: 1