Advertisement
joris

Function

Jul 31st, 2017
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict'
  2.  
  3. const functions = require('firebase-functions');
  4. const admin = require('firebase-admin');
  5. admin.initializeApp(functions.config().firebase);
  6.  
  7. exports.sendNotification = functions.database.ref('/Notifications/{user_id}/{notification_id}').onWrite(event => {
  8.    
  9.     const user_id = event.params.user_id;
  10.     const notification_id = event.params.notification_id;
  11.    
  12.     console.log('User ID is : ', user_id);
  13.     console.log('Notification ID is : ', notification_id);
  14.    
  15.     if(!event.data.val()) {
  16.         return console.log('A Notification has been deleted from database. Sender : ', notification_id);
  17.     }
  18.    
  19.     const fromUser = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
  20.     return fromUser.then(fromUserResult => {
  21.        
  22.         const from_user_id = fromUserResult.val().from;
  23.        
  24.         console.log("You have a new request from : ", from_user_id);
  25.        
  26.         const userQuery = admin.database().ref(`/Users/${from_user_id}/name`).once('value');
  27.         return userQuery.then(userResult => {
  28.            
  29.             const userName = userResult.val();
  30.            
  31.             const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
  32.             return deviceToken.then(result => {
  33.                
  34.                 const token_id = result.val();
  35.                 console.log('Token ID is : ', token_id);
  36.                
  37.                 const payload = {
  38.                     notification: {
  39.                         title: "New Friend Request",
  40.                         body: `${userName} has sent you Friend Request`,
  41.                         icon: "default",
  42.                         click_action: "com.bertho.chat_TARGET_NOTIFICATION"
  43.                     },
  44.                     data: {
  45.                         from_user_id: from_user_id
  46.                     }
  47.                 };
  48.                
  49.                 console.log('SENT FROM : ', from_user_id);
  50.            
  51.                 return admin.messaging().sendToDevice(token_id, payload).then(response => {
  52.                     console.log('This was the Notification Feature');
  53.                 });
  54.                
  55.             });
  56.            
  57.         });
  58.     });
  59.    
  60. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement