Created
April 9, 2018 07:43
-
-
Save DroidLove/df323301b1f37dc75a8cab1abb87aa04 to your computer and use it in GitHub Desktop.
Firebase cloud function accesing Database plus trigger Push notification
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
var functions = require('firebase-functions'); | |
var admin = require('firebase-admin'); | |
var serviceAccount = require("./serviceAccountKey.json"); | |
// admin.initializeApp(functions.config().firebase); | |
admin.initializeApp({ | |
credential: admin.credential.cert(serviceAccount), | |
databaseURL: "https://tutsalert.firebaseio.com" | |
}); | |
exports.sendNotification = functions.database.ref('/articles/{articleId}') | |
.onWrite((change, context) => { | |
// Grab the current value of what was written to the Realtime Database. | |
// var eventSnapshot = event.data.ref; | |
var str1 = "Author is "; | |
// var str = str1.concat(eventSnapshot.child("author").val()); | |
console.log(str1+change.after.val()); | |
var topic = "android"; | |
var payload = { | |
data: { | |
title: change.after.child("title").val(), | |
author: change.after.child("author").val() | |
} | |
}; | |
// Send a message to devices subscribed to the provided topic. | |
return admin.messaging().sendToTopic(topic, payload) | |
.then(function (response) { | |
// See the MessagingTopicResponse reference documentation for the | |
// contents of response. | |
console.log("Successfully sent message:", response); | |
}) | |
.catch(function (error) { | |
console.log("Error sending message:", error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment