implement ready up for players in a game lobby
This commit is contained in:
60
src/routes/api/games/[gameid]/players/[playerid]/+server.ts
Normal file
60
src/routes/api/games/[gameid]/players/[playerid]/+server.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import type { GameData } from "$lib/GameData";
|
||||
import { isGamePlayer, type GamePlayer } from "$lib/GamePlayer";
|
||||
import { isListing } from "$lib/Listing";
|
||||
import { Game } from "$lib/server/Game";
|
||||
import { updateListing } from "$lib/server/modifyListing";
|
||||
import {
|
||||
readListingById,
|
||||
ServerCollections,
|
||||
writeUpdatedListing,
|
||||
} from "$lib/server/mongo";
|
||||
import { getBody, getParam, ResourceId } from "$lib/server/requestTools";
|
||||
import {
|
||||
badRequestResponse,
|
||||
conflictResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from "$lib/server/responseBodies";
|
||||
import type { RequestHandler } from "@sveltejs/kit";
|
||||
|
||||
export const PUT: RequestHandler = async ({ params, request }): Promise<Response> => {
|
||||
const id = getParam(params, ResourceId.Game);
|
||||
|
||||
if (id === null) {
|
||||
return badRequestResponse("missing playerid parameter");
|
||||
}
|
||||
|
||||
let player: GamePlayer | null;
|
||||
try {
|
||||
player = await getBody(request, isGamePlayer);
|
||||
} catch (err) {
|
||||
return badRequestResponse("missing player body");
|
||||
}
|
||||
|
||||
if (!player) {
|
||||
return badRequestResponse("malformed request");
|
||||
}
|
||||
|
||||
const listing = await readListingById(ServerCollections.Games, id, isListing<GameData>);
|
||||
if (!listing) {
|
||||
return notFoundResponse();
|
||||
}
|
||||
|
||||
if (listing.data.isStarted === true) {
|
||||
return conflictResponse();
|
||||
}
|
||||
|
||||
const game = Game.from(listing.data);
|
||||
if (game.setPlayerReady(player) === null) return notFoundResponse();
|
||||
|
||||
// TODO: there's a potential race condition here where some player is unreadying as this
|
||||
// function is running. This should do some kind of check in MongoDB to make sure
|
||||
// all players are ready if it's starting the game. For now: good enough.
|
||||
if (game.players.every(({ isReady }) => isReady)) {
|
||||
game.start();
|
||||
}
|
||||
|
||||
await writeUpdatedListing(ServerCollections.Games, updateListing(listing, game));
|
||||
|
||||
return singleResponse(game);
|
||||
};
|
Reference in New Issue
Block a user