Skip to content

Instantly share code, notes, and snippets.

@kostapappas
Last active May 9, 2020 11:44
Show Gist options
  • Save kostapappas/22029d9144a61c3c03e8974482673eb9 to your computer and use it in GitHub Desktop.
Save kostapappas/22029d9144a61c3c03e8974482673eb9 to your computer and use it in GitHub Desktop.
Firebase javascript function to send push notification when a new item added in firestore
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
exports.notifyNewMessage = functions.firestore
.document('365BetaCannels2/{chanl}/thrad/{messe}')
.onCreate((docSnapshot, context) => {
const message = docSnapshot.data();
const recipientId = message['recipientID'];
const senderFirstName = message['senderFirstName'];
const senderLastName = message['senderLastName'];
return admin.firestore().doc('PhowUsers/' + recipientId)
.get().then(userDoc => {
const registrationTokens = userDoc.get('firebaseCloudMessagingTokens');
const notificationBody = (message['content']) ? message['content'] : "You received a new image message" ;
const payload = {
notification: {
title: senderFirstName + " " + senderLastName + " sent you a message.",
body: notificationBody,
clickAction: "ChatActivity"
},
data: {
USER_NAME: senderFirstName,
USER_ID: message['senderID']
}
};
return admin.messaging().sendToDevice(registrationTokens, payload).then(
response => {
const stillRegisteredTokens = registrationTokens;
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
const failedToken = registrationTokens[index];
console.error('invalid token will be removed automatically', failedToken, error);
if (error.code === 'messaging/invalid-registration-token' || error.code ==='messaging/registration-token-not-registered'){
const failedIndex = stillRegisteredTokens.indexOf(failedToken);
if (failedIndex > -1) {
stillRegisteredTokens.splice(failedIndex, 1);
}
}
}
});
return admin.firestore().doc("PholowUsers/" + recipientId).update({
firebaseCloudMessagingTokens: stillRegisteredTokens
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment