Skip to content

Instantly share code, notes, and snippets.

@quangquy87
Forked from naumanahmed19/index.js
Created April 10, 2020 02:40
Show Gist options
  • Save quangquy87/dbf5146cfc472fa21527e6b5dc5c4706 to your computer and use it in GitHub Desktop.
Save quangquy87/dbf5146cfc472fa21527e6b5dc5c4706 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