Guest User

Untitled

a guest
Nov 17th, 2017
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. let functions = require('firebase-functions');
  2.  
  3. let admin = require('firebase-admin');
  4.  
  5. admin.initializeApp(functions.config().firebase);
  6.  
  7. exports.sendNotification = functions.database.ref('/messages/{userId}/{messageId}').onWrite(event => {
  8.  
  9. //get the userId of the person receiving the notification because we need to get their token
  10. const receiverId = event.params.userId;
  11. console.log("receiverId: ", receiverId);
  12.  
  13. //get the user id of the person who sent the message
  14. const senderId = event.data.child('user_id').val();
  15. console.log("senderId: ", senderId);
  16.  
  17. //get the message
  18. const message = event.data.child('message').val();
  19. console.log("message: ", message);
  20.  
  21. //get the message id. We'll be sending this in the payload
  22. const messageId = event.params.messageId;
  23. console.log("messageId: ", messageId);
  24.  
  25. //query the users node and get the name of the user who sent the message
  26. return admin.database().ref("/users/" + senderId).once('value').then(snap => {
  27. const senderName = snap.child("name").val();
  28. console.log("senderName: ", senderName);
  29.  
  30. //get the token of the user receiving the message
  31. return admin.database().ref("/users/" + receiverId).once('value').then(snap => {
  32. const token = snap.child("messaging_token").val();
  33. console.log("token: ", token);
  34.  
  35. //we have everything we need
  36. //Build the message payload and send the message
  37. console.log("Construction the notification message.");
  38. const payload = {
  39. data: {
  40. data_type: "direct_message",
  41. title: "New Message from " + senderName,
  42. message: message,
  43. message_id: messageId,
  44. }
  45. };
  46.  
  47. return admin.messaging().sendToDevice(token, payload)
  48. .then(function(response) {
  49. console.log("Successfully sent message:", response);
  50. })
  51. .catch(function(error) {
  52. console.log("Error sending message:", error);
  53. });
  54. });
  55. });
  56. });
Add Comment
Please, Sign In to add comment