Skip to content

Instantly share code, notes, and snippets.

@naumanahmed19
Created October 7, 2018 22:19
Show Gist options
  • Save naumanahmed19/d37881f5df3f6f074c4fb7d0d9672d51 to your computer and use it in GitHub Desktop.
Save naumanahmed19/d37881f5df3f6f074c4fb7d0d9672d51 to your computer and use it in GitHub Desktop.
Firebase Firestore Cloud Messaging(Notification) Server Function
const functions = require("firebase-functions");
var request = require("request");
var API_KEY = "YOUR-API-KEY"; // Your Firebase Cloud Messaging Server API key
function sendNotificationToUser(userId, message) {
request(
{
url: "https://fcm.googleapis.com/fcm/send",
method: "POST",
headers: {
"Content-Type": " application/json",
Authorization: "key=" + API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to: "/topics/user-" + userId
})
},
function(error, response, body) {
if (error) {
console.error(error);
} else if (response.statusCode >= 400) {
console.error(
"HTTP Error: " + response.statusCode + " - " + response.statusMessage
);
}
}
);
}
exports.notificationCreate = functions.firestore
.document("/notifications/{id}")
.onCreate((snapshot, context) => {
const data = snapshot.data();
sendNotificationToUser(data.userId, data.message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment