Skip to content

Instantly share code, notes, and snippets.

@kolyabres
Created December 2, 2018 09:37
Show Gist options
  • Save kolyabres/e76250bd77d424382876afcbe219ddfb to your computer and use it in GitHub Desktop.
Save kolyabres/e76250bd77d424382876afcbe219ddfb to your computer and use it in GitHub Desktop.
notifications
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const errors = (e) => {
console.log('catch', e)
}
exports.sendNotification = functions.database.ref("/messages/{id}").onWrite(( change,context) => {
const message = change.after.val();
return admin.database()
.ref("/chats")
.child(message.chatId)
.once("value")
.then(function(snapshot) {
const chat = snapshot.val();
const chatUsers = Object.keys(chat.users).map(function(key) {
return chat.users[key];
});
const massageFrom = chatUsers.find(user => user.userId === message.userId).userName
const userIds = Object.keys(chat.users);
const filteredIds = userIds.filter(userId => userId !== message.userId);
const payload = {
notification: {
title: massageFrom,
body: message.text
},
data: {
event: "MESSAGE",
chatId: message.chatId,
messageTitle: massageFrom,
messageBody: message.text
}
};
var promises = filteredIds.map(function(userId) {
return admin.database().ref("/fcmTokens/").child(userId).once("value");
});
Promise.all(promises).then(function(tokenSnapshots) {
tokenSnapshots.forEach(function(tokenSnapshot) {
console.log(tokenSnapshot.key + " : " + tokenSnapshot.val());
const token = tokenSnapshot.val()
if (token !== null) {
admin.messaging().sendToDevice(token, payload).then(response => {
return console.log("Notification Sent");
}).catch(errors);
} else {
return console.log("Firebase token not found");
}
});
return console.log("promise");
}).catch(errors);
return console.log("return");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment