Skip to content

Commit

Permalink
Fix NPE in finishGame
Browse files Browse the repository at this point in the history
Apparently, transaction handlers are very often called with null even if
the object exists as an optimization. See:

https://groups.google.com/g/firebase-talk/c/Lyb0KlPdQEo
https://stackoverflow.com/a/65415636/5190601

Fixes: #4
  • Loading branch information
eltoder committed Nov 18, 2024
1 parent a82cf36 commit 9fa97d5
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,6 @@ export const finishGame = functions.https.onCall(async (data, context) => {
.ref(`gameData/${gameId}`)
.once("value");
const gameSnap = await admin.database().ref(`games/${gameId}`).once("value");
if (!gameSnap.exists()) {
throw new functions.https.HttpsError(
"not-found",
`The game with gameId ${gameId} was not found in the database.`
);
}

const gameMode = (gameSnap.child("mode").val() as GameMode) || "normal";

const { lastSet, deck, finalTime, scores } = replayEvents(gameData, gameMode);
Expand All @@ -73,6 +66,14 @@ export const finishGame = functions.https.onCall(async (data, context) => {
.database()
.ref(`games/${gameId}`)
.transaction((game) => {
// Transaction handler should always handle null, because firebase often
// calls it like that: https://stackoverflow.com/a/65415636/5190601
if (game === null) {
throw new functions.https.HttpsError(
"not-found",
`The game with gameId ${gameId} was not found in the database.`
);
}
if (game.status !== "ingame") {
// Someone beat us to the atomic update, so we cancel the transaction.
return;
Expand Down

0 comments on commit 9fa97d5

Please sign in to comment.