-
-
Save ebinabo/51b1603ae6da96a6509fe7fccac0493e to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging + Cloud Functions
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
| const functions = require('firebase-functions'); | |
| const admin = require('firebase-admin'); | |
| admin.initializeApp(); | |
| exports.sendLeaderboardMesssage = functions | |
| .database | |
| .ref('/leaderboard/{position}') | |
| .onUpdate((change) => { | |
| const oldPlayer = change.before.val(); | |
| const newPlayer = change.after.val(); | |
| // Exit if change is caused by old player moving up in leaderboard | |
| if (newPlayer.score <= oldPlayer.score) { return; } | |
| const payload = { | |
| notification: { | |
| title: `${oldPlayer.handle}, ${newPlayer.handle} just beat your score!`, | |
| body: 'Play now to get back on the leaderboard', | |
| } | |
| }; | |
| const databaseRoot = change.before.ref.root; | |
| return databaseRoot.child('users/' + oldPlayer.uId).once('value') | |
| .then(snapshot => { | |
| const fcmToken = snapshot.val().fcmToken; | |
| return admin.messaging().sendToDevice(fcmToken, payload); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment