Created
April 26, 2017 11:12
-
-
Save biodunalfet/9118721bfb8979f5ff1a660460058357 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var functions = require('firebase-functions'); | |
var admin = require('firebase-admin'); | |
admin.initializeApp(functions.config().firebase); | |
exports.sendNotificationOnEventComment | |
= functions.database.ref('/eventComments/{eventUid}/{eventCommentUid}').onWrite(event => { | |
if (event.data.exists()) { | |
var eventUid = event.params.eventUid; | |
var eventCommentUid = event.params.eventCommentUid; | |
console.log("event id is", eventUid); | |
console.log("event comment id is", eventCommentUid); | |
console.log("event comment is", event.data.val()); | |
var comments = event.data.val(); | |
var commenter = comments.senderName; | |
console.log("commenter is", commenter); | |
var payload = { | |
notification : { | |
title : "" | |
} | |
}; | |
var eventPromise = admin.database().ref('/events/' + eventUid).once("value"); | |
eventPromise | |
.then(function (resultSnap) { | |
if (resultSnap.exists()) { | |
var eventData = resultSnap.val(); | |
console.log("event is", eventData); | |
return eventData; | |
} | |
}) | |
.then(function (eventData){ | |
if (eventData) { | |
payload.notification.title = "New comment on event " | |
+ eventData.name + " by " + commenter; | |
console.log("event payload", payload.notification.title); | |
var invitees = eventData.invitees; | |
console.log("invitees are ", invitees); | |
var fcmTokenPromises = invitees.map(retrieveFcmToken); | |
return Promise.all(fcmTokenPromises).then(function(results){ | |
console.log("token promise result ", results); | |
tokens = []; | |
results.forEach(function(item){ | |
if (item.val()) { | |
tokens.push(item.val()); | |
console.log('token', item.val()); | |
} | |
}); | |
admin.messaging().sendToDevice(tokens, payload) | |
.then(function(response) { | |
console.log("Successfully sent message:", response); | |
}) | |
.catch(function(error) { | |
console.log("Error sending message:", error); | |
}); | |
}) | |
.catch(function (err){ | |
console.log("error is", err); | |
}); | |
} | |
}); | |
} | |
}); | |
var retrieveFcmToken = function(Uid) { | |
return admin.database().ref('/users/' + Uid + '/fcmToken').once('value'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment