Last active
September 19, 2019 14:03
-
-
Save MohammedFouad/c978c4cf56c2d28c4373cc1c8c141c73 to your computer and use it in GitHub Desktop.
This code is for device to device firebase notifications, Thanks for TVAC Studio channel for great tutorial on youtube https://www.youtube.com/watch?v=Abh3r9hh5gw&list=PLGCjwl1RrtcRHjHyZAxm_Mq4qvtnundo0&index=4
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
'use strict' | |
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. | |
const functions = require('firebase-functions'); | |
// The Firebase Admin SDK to access the Firebase Realtime Database. | |
const admin = require('firebase-admin'); | |
admin.initializeApp(); | |
exports.sendNotification = functions.firestore.document('Users/{user_id}/Notifications/{notification_id}').onWrite ((change, context) => { | |
const user_id = context.params.user_id; | |
const notification_id = context.params.notification_id; | |
console.log(" user_id " + user_id); | |
console.log("notification_id" + notification_id); | |
return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult=> { | |
const from_user_id = queryResult.data().from; | |
const from_message = queryResult.data().message; | |
const from_data = admin.firestore().collection("Users").doc(from_user_id).get(); | |
const to_data = admin.firestore().collection("Users").doc(user_id).get(); | |
return Promise.all([from_data, to_data]).then(results =>{ | |
const from_name = results[0].data().name; | |
const to_name = results[1].data().name; | |
const token_id = results[1].data().token_id; | |
console.log("from :"+ from_name+" To "+ to_name); | |
const payLoad = { | |
notification: { | |
title : "Notification From: " + from_name, | |
body : from_message, | |
icon : "default" | |
} | |
} | |
return admin.messaging().sendToDevice(token_id,payLoad).then(results=>{ | |
console.log("Notification sent") | |
return true; | |
}); | |
}); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment