Skip to content

Instantly share code, notes, and snippets.

@FilipeLipan
Last active November 7, 2017 18:25
Show Gist options
  • Save FilipeLipan/82bd474bd947c6d68c4e55cb03c30e68 to your computer and use it in GitHub Desktop.
Save FilipeLipan/82bd474bd947c6d68c4e55cb03c30e68 to your computer and use it in GitHub Desktop.
even-functions-push
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/snptee/inbox/{userUiid}/{chatId}/{lastMessage}').onWrite(event => {
let userUiid = event.params.userUiid;
let chatId = event.params.chatId;
var lastMessage = event.data.val();
if(event.params.userUiid === lastMessage.destinataryId){
return admin.database().ref('/snptee/profile/' + lastMessage.destinataryId ).once('value').then((fcmTokens) => {
const tokensValue =fcmTokens.val();
const tokensRaw = Object.keys(tokensValue);
var iosTokens = [];
var androidTokens = [];
for (var i = 0; i < tokensRaw.length; i++) {
var key = tokensRaw[i];
var t = tokensValue[key];
if(t.type === 'android'){
androidTokens.push(tokensRaw[i]);
}
if(t.type === 'ios'){
iosTokens.push(tokensRaw[i]);
}
}
if(androidTokens.length > 0){
let payloadAndroid = {
notification: {
title: lastMessage.displayName + "",
body: lastMessage.message + "",
sound: 'default',
icon: 'ic_logo'
}
};
admin.messaging().sendToDevice(androidTokens, payloadAndroid);
}
if(iosTokens.length > 0){
let payloadIos = {
notification: {
title: lastMessage.displayName + "",
body: lastMessage.message + "",
sound: 'default',
icon: 'ic_logo'
}
};
admin.messaging().sendToDevice(iosTokens, payloadIos);
}
})
}
return Promise.reject(new Error("Mismatch 'from' and 'to' UIID"));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment