Skip to content

Instantly share code, notes, and snippets.

@Bahaaib
Created January 29, 2019 13:20
Show Gist options
  • Select an option

  • Save Bahaaib/f807e2eb6db6a596bd8ced21df1c04e1 to your computer and use it in GitHub Desktop.

Select an option

Save Bahaaib/f807e2eb6db6a596bd8ced21df1c04e1 to your computer and use it in GitHub Desktop.
Firebase Node js function that pushes notifications upon listening to database change
//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