Last active
April 22, 2022 10:41
-
-
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
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(); | |
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