Skip to content

Instantly share code, notes, and snippets.

@laurenzlong
Last active October 4, 2021 04:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save laurenzlong/921c17af0d0350d27c6a7f4522bbe685 to your computer and use it in GitHub Desktop.
Save laurenzlong/921c17af0d0350d27c6a7f4522bbe685 to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging + Cloud Functions
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);
});
});
@MaffooBristol
Copy link

Thank you for this Lauren 👍

@laurenzlong
Copy link
Author

You're welcome!

@poojaba
Copy link

poojaba commented Jun 2, 2020

Thanks for code lauren! How can I use it with Firestore when my score is saved in structure like this?

score/{userId}/subject/{quizResultId}/

@laurenzlong
Copy link
Author

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

@poojaba
Copy link

poojaba commented Jun 6, 2020

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