Last active
October 4, 2021 04:55
-
-
Save laurenzlong/921c17af0d0350d27c6a7f4522bbe685 to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging + Cloud Functions
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'); | |
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); | |
}); | |
}); |
Thanks for reply @laurenzlong. I have subject wise high scores at user document like this:
users/{userID}
fields (key - value):
history - 120
science - 150
total - 270
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @poojaba, thanks for the comment! It doesn't seem like your data is a high score board, rather it seems to be storing individual quiz results for each user. So you can't directly use this code. I recommend checking out documentation for database functions to learn how to write a function that suits your use case: https://firebase.google.com/docs/functions/database-events