Skip to content

Instantly share code, notes, and snippets.

@ashishbeck
Last active April 22, 2022 10:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashishbeck/2f5f3d1ab376d09a5cb5445b751380e8 to your computer and use it in GitHub Desktop.
Save ashishbeck/2f5f3d1ab376d09a5cb5445b751380e8 to your computer and use it in GitHub Desktop.
Firebase Cloud Function to keep the community scores updated for my slide puzzle project at https://github.com/ashishbeck/slide_puzzle
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;
exports.updateScores = functions.firestore
.document("users/{userId}")
.onUpdate((change, context) => {
const newValue = change.after.data();
const oldValue = change.before.data();
const newMoves = newValue.moves;
const newTimes = newValue.times;
const oldMoves = oldValue.moves;
const oldTimes = oldValue.times;
const gridSize = ["three", "four"];
gridSize.forEach(grid => {
const newMove = newMoves[grid];
const oldMove = oldMoves[grid];
const newTime = newTimes[grid];
const oldTime = oldTimes[grid];
if (newMove != oldMove) {
const isOldZero = oldMove == 0;
let payload = {};
payload[`${grid}.${newMove}`] = FieldValue.increment(1);
if (!isOldZero) {
payload[`${grid}.${oldMove}`] = FieldValue.increment(-1);
}
db.collection("community").doc("moves").update(payload);
// console.log("data updated " + grid + ", " + JSON.stringify(payload));
}
if (newTime != oldTime) {
const isOldZero = oldTime == 0;
let payload = {};
payload[`${grid}.${newTime}`] = FieldValue.increment(1);
if (!isOldZero) {
payload[`${grid}.${oldTime}`] = FieldValue.increment(-1);
}
db.collection("community").doc("times").update(payload);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment