Skip to content

Commit

Permalink
Feature/remove server state (#99)
Browse files Browse the repository at this point in the history
* feat: remove server timeout progression

* feat: clean nudge-game route

* feat: add planned game nudge on time getting to 0

* feat: convert create-game from api to action

* feat: convert nudge game from api route to action

* feat: remove unknownParser from actions

* feat: convert create game api to action

* refactor: move start-game api to action

* refactor: convert update answer api to action

* refactor: change exit-game api to action

* refactor: move actions out of folders

* refactor: remove custom zod-parser

* refactor: remove time-calculator

* feat: improve visual cues for correct answers
  • Loading branch information
LukeSchlangen authored Aug 24, 2023
1 parent b2f863f commit 9488bde
Show file tree
Hide file tree
Showing 30 changed files with 449 additions and 665 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default function GamePage() {
</>)}
{gameRef && <>
{isShowingQuestion && (<QuestionPanel game={game} gameRef={gameRef} currentQuestion={currentQuestion} />)}
{game.state === gameStates.NOT_STARTED && (<Lobby game={game} gameRef={gameRef} />)}
{game.state === gameStates.NOT_STARTED && (<Lobby game={game} gameId={gameId} />)}
</>}
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,48 +14,40 @@
* limitations under the License.
*/

import {unknownParser, unknownValidator} from '@/app/lib/zod-parser';
import {gamesRef, questionsRef} from '@/app/lib/firebase-server-initialization';
'use server';

import {app, gamesRef, questionsRef} from '@/app/lib/firebase-server-initialization';
import {generateName} from '@/app/lib/name-generator';
import {getAuthenticatedUser} from '@/app/lib/server-side-auth';
import {Game, Question, QuestionSchema, gameStates} from '@/app/types';
import {Game, GameSettings, Question, QuestionSchema, gameStates} from '@/app/types';
import {QueryDocumentSnapshot, Timestamp} from 'firebase-admin/firestore';
import {NextRequest, NextResponse} from 'next/server';
import {authenticationFailedResponse} from '@/app/lib/authentication-failed-response';
import {GameSettingsSchema} from '@/app/types';
import {badRequestResponse} from '@/app/lib/bad-request-response';

export async function POST(request: NextRequest) {
let authUser;
try {
authUser = await getAuthenticatedUser(request);
} catch (error) {
return authenticationFailedResponse();
}
import {getAuth} from 'firebase-admin/auth';

// Validate request
const body = await request.json();
const errorMessage = unknownValidator(body, GameSettingsSchema);
if (errorMessage) return badRequestResponse({errorMessage});
const {timePerQuestion, timePerAnswer} = unknownParser(body, GameSettingsSchema);
export async function createGameAction({gameSettings, token}: {gameSettings: GameSettings, token: string}): Promise<{gameId: string}> {
const authUser = await getAuth(app).verifyIdToken(token);

// Parse request (throw an error if not correct)
const {timePerQuestion, timePerAnswer} = GameSettingsSchema.parse(gameSettings);

const querySnapshot = await questionsRef.get();
const validQuestionsArray = querySnapshot.docs.reduce((agg: Question[], doc: QueryDocumentSnapshot) => {
const question = doc.data();
const errorMessage = unknownValidator(question, QuestionSchema);
if (errorMessage) {
let question = doc.data();
try {
question = QuestionSchema.parse(question);
return [...agg, question];
} catch (error) {
console.warn(`WARNING: The question "${question?.prompt}" [Firestore ID: ${doc.id}] has an issue and will not be added to the game.`);
return agg;
}
return [...agg, question];
}, []);

// convert array to object for Firebase
const questions = {...validQuestionsArray};
if (!authUser) throw new Error('User must be signed in to start game');

// create game with server endpoint

const leader = {
displayName: generateName(),
displayName: generateName(authUser.uid),
uid: authUser.uid,
};

Expand All @@ -74,5 +66,7 @@ export async function POST(request: NextRequest) {

const gameRef = await gamesRef.add(newGame);

return NextResponse.json({gameId: gameRef.id}, {status: 200});
if (gameRef.id) return {gameId: gameRef.id};

throw new Error('no gameId returned in the response');
}
41 changes: 41 additions & 0 deletions app-dev/party-game/app/actions/delete-game.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use server';

import {app, gamesRef} from '@/app/lib/firebase-server-initialization';
import {GameIdSchema} from '@/app/types';
import {getAuth} from 'firebase-admin/auth';

export async function deleteGameAction({gameId, token}: {gameId: string, token: string}) {
// Authenticate user
const authUser = await getAuth(app).verifyIdToken(token);

// Parse request (throw an error if not correct)
GameIdSchema.parse(gameId);

const gameRef = await gamesRef.doc(gameId);
const gameDoc = await gameRef.get();
const game = gameDoc.data();

if (game.leader.uid !== authUser.uid) {
// Respond with JSON indicating no game was found
throw new Error('Only the leader of this game may delete this game.');
}

// update database to delete the game
await gameRef.delete();
}
37 changes: 37 additions & 0 deletions app-dev/party-game/app/actions/exit-game.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use server';

import {app, gamesRef} from '@/app/lib/firebase-server-initialization';
import {FieldValue} from 'firebase-admin/firestore';
import {GameIdSchema} from '@/app/types';
import {getAuth} from 'firebase-admin/auth';

export async function exitGameAction({gameId, token}: {gameId: string, token: string}) {
// Authenticate user
const authUser = await getAuth(app).verifyIdToken(token);

// Parse request (throw an error if not correct)
GameIdSchema.parse(gameId);

const gameRef = await gamesRef.doc(gameId);

// update database to exit the game
await gameRef.update({
[`players.${authUser.uid}`]: FieldValue.delete(),
});
}
45 changes: 45 additions & 0 deletions app-dev/party-game/app/actions/join-game.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use server';

import {app, gamesRef} from '@/app/lib/firebase-server-initialization';
import {generateName} from '@/app/lib/name-generator';
import {GameIdSchema} from '@/app/types';
import {getAuth} from 'firebase-admin/auth';

export async function joinGameAction({gameId, token}: {gameId: string, token: string}) {
// Authenticate user
const authUser = await getAuth(app).verifyIdToken(token);

// Parse request (throw an error if not correct)
GameIdSchema.parse(gameId);

const gameRef = await gamesRef.doc(gameId);
const gameDoc = await gameRef.get();
const game = gameDoc.data();
const playerIdList = Object.keys(game.players);
if (playerIdList.includes(authUser.uid)) return;
if (game.leader.uid === authUser.uid) {
// Respond with JSON indicating no game was found
throw new Error('The game leader may not be a player.');
}

// update database to join the game
await gameRef.update({
[`players.${authUser.uid}`]: generateName(authUser.uid),
});
}
57 changes: 57 additions & 0 deletions app-dev/party-game/app/actions/nudge-game.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use server';

import {gamesRef} from '@/app/lib/firebase-server-initialization';
import {GameIdSchema, gameStates} from '@/app/types';
import {Timestamp} from 'firebase-admin/firestore';

export async function nudgeGame({gameId}: {gameId: string}) {
// Validate request
// Will throw an error if not a string
GameIdSchema.parse(gameId);

const gameRef = await gamesRef.doc(gameId);
const gameDoc = await gameRef.get();
const game = gameDoc.data();

// force the game state to move to where the game should be

const timeElapsedInMillis = Timestamp.now().toMillis() - game.startTime.seconds * 1000;
const timeElapsed = timeElapsedInMillis / 1000;
const timePerQuestionAndAnswer = game.timePerQuestion + game.timePerAnswer;

const totalNumberOfQuestions = Object.keys(game.questions).length;
const finalQuestionIndex = totalNumberOfQuestions - 1;
const correctQuestionIndex = Math.floor(timeElapsed / timePerQuestionAndAnswer);
if (correctQuestionIndex > finalQuestionIndex) {
await gameRef.update({
state: gameStates.GAME_OVER,
currentQuestionIndex: finalQuestionIndex,
});
return;
}

const timeThisQuestionStarted = correctQuestionIndex * timePerQuestionAndAnswer;
const shouldBeAcceptingAnswers = timeElapsed - timeThisQuestionStarted < game.timePerQuestion;
const correctState = shouldBeAcceptingAnswers ? gameStates.AWAITING_PLAYER_ANSWERS : gameStates.SHOWING_CORRECT_ANSWERS;

await gameRef.update({
state: correctState,
currentQuestionIndex: correctQuestionIndex,
});
}
45 changes: 45 additions & 0 deletions app-dev/party-game/app/actions/start-game.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use server';

import {app, gamesRef} from '@/app/lib/firebase-server-initialization';
import {GameIdSchema, gameStates} from '@/app/types';
import {FieldValue} from 'firebase-admin/firestore';
import {getAuth} from 'firebase-admin/auth';

export async function startGameAction({gameId, token}: {gameId: string, token: string}) {
// Authenticate user
const authUser = await getAuth(app).verifyIdToken(token);

// Parse request (throw an error if not correct)
GameIdSchema.parse(gameId);

const gameRef = await gamesRef.doc(gameId);
const gameDoc = await gameRef.get();
const game = gameDoc.data();

if (game.leader.uid !== authUser.uid) {
// Respond with JSON indicating no game was found
throw new Error('Only the leader of this game may start this game.');
}

// update database to start the game
await gameRef.update({
state: gameStates.AWAITING_PLAYER_ANSWERS,
startTime: FieldValue.serverTimestamp(),
});
}
48 changes: 48 additions & 0 deletions app-dev/party-game/app/actions/update-answer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use server';

import {app, gamesRef} from '@/app/lib/firebase-server-initialization';
import {GameIdSchema, gameStates} from '@/app/types';
import {getAuth} from 'firebase-admin/auth';
import {z} from 'zod';

export async function updateAnswerAction({gameId, answerSelection, token}: {gameId: string, answerSelection: boolean[], token: string}) {
// Authenticate user
const authUser = await getAuth(app).verifyIdToken(token);

// Parse request (throw an error if not correct)
GameIdSchema.parse(gameId);

const gameRef = await gamesRef.doc(gameId);
const gameDoc = await gameRef.get();
const game = gameDoc.data();

if (game.state !== gameStates.AWAITING_PLAYER_ANSWERS) {
return new Error(`Answering is not allowed during ${game.state}.`);
}

// answerSelection must be an array of booleans as long as the game question answers
const currentQuestion = game.questions[game.currentQuestionIndex];
const ValidAnswerSchema = z.array(z.boolean()).length(currentQuestion.answers.length);
ValidAnswerSchema.parse(answerSelection);

// update database to start the game
await gameRef.update({
[`questions.${game.currentQuestionIndex}.playerGuesses.${authUser.uid}`]: answerSelection,
});
}
Loading

0 comments on commit 9488bde

Please sign in to comment.