Created
January 29, 2019 13:20
-
-
Save Bahaaib/f807e2eb6db6a596bd8ced21df1c04e1 to your computer and use it in GitHub Desktop.
Firebase Node js function that pushes notifications upon listening to database change
This file contains hidden or 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
| //import firebase functions modules | |
| const functions = require('firebase-functions'); | |
| //import admin module | |
| const admin = require('firebase-admin'); | |
| admin.initializeApp(functions.config().firebase); | |
| // Listens for new messages added to messages/:pushId | |
| exports.notificationSender = functions.database.ref('/messages/{pushId}').onWrite((change,context) => { | |
| console.log('Message Received'); | |
| // Grab the current value of what was written to the Realtime Database. | |
| const valueObject = change.after.val(); | |
| // Create a notification | |
| const payload = { | |
| notification: { | |
| title:valueObject.title, | |
| body: valueObject.message, | |
| sound: "default" | |
| }, | |
| }; | |
| //Create an options object that contains the time to live for the notification and the priority | |
| const options = { | |
| priority: "high", | |
| timeToLive: 60 * 60 * 24 | |
| }; | |
| return admin.messaging().sendToTopic("messages", payload, options); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment