I am trying to send a notification to an android device using firebase cloud messaging.
Below is sendNotification
which is a cloud function I have deployed on firebase:
const sendNotification = (owner_uid: any, type: any) => {
return new Promise((resolve, reject) => {
admin.firestore().collection('users').doc(owner_uid).get().then((doc) => {
if (doc.exists && doc.data()?.token) {
if (type === 'new_comment') {
console.log('NEW COMMENT');
console.log('TOKEN: ' + doc.data()?.token);
admin.messaging().sendToDevice(doc.data()?.token, {
data: {
title: 'A new comment has been made on your post',
}
}).then((sent) => {
console.log("SENT COUNT " + sent.successCount);
console.log('SENT APPARENTLY')
resolve(sent);
});
}
}
});
});
}
And here is where I'm calling this function:
export const updateCommentsCount = functions.firestore.document('comments/{commentId}').onCreate(async (event) => {
const data = event.data();
const postId = data?.post;
const doc = await admin.firestore().collection('posts').doc(postId).get();
if (doc.exists) {
let commentsCount = doc.data()?.commentsCount || 0;
commentsCount++;
await admin.firestore().collection('posts').doc(postId).update({
'commentsCount': commentsCount
})
return sendNotification(doc.data()?.owner, 'new_comment');
} else {
return false;
}
})
However, I'm not receiving a notification on the android device.
And here are the cloud function logs when I leave a comment:
Can someone please tell me why is happening, & how it can be resolved? I can show further code if required.
I managed to find the solution.
In the notification sending method, sendToDevice, I updated the key "data", to "notification" and the notification is now being automatically sent & displayed on the original user's device.
Here is the updated
admin.messaging().sendToDevice(doc.data()?.token, {
notification: {
title: 'A new comment has been made on your post',
}