Created
October 7, 2018 22:19
-
-
Save naumanahmed19/d37881f5df3f6f074c4fb7d0d9672d51 to your computer and use it in GitHub Desktop.
Firebase Firestore Cloud Messaging(Notification) Server Function
This file contains 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
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