71 lines
1.8 KiB
TypeScript
71 lines
1.8 KiB
TypeScript
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 { retry } from "$lib/server/retry";
|
|
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 putItem = async (): Promise<[boolean, Response]> => {
|
|
const listing = await readListingById(
|
|
ServerCollections.Games,
|
|
id,
|
|
isListing<GameData>,
|
|
);
|
|
|
|
if (!listing) {
|
|
return [false, notFoundResponse()];
|
|
}
|
|
|
|
if (listing.data.isStarted === true) {
|
|
return [false, conflictResponse()];
|
|
}
|
|
|
|
const game = Game.from(listing.data);
|
|
if (game.setPlayerReady(player) === null) return [false, notFoundResponse()];
|
|
|
|
const res = await writeUpdatedListing(
|
|
ServerCollections.Games,
|
|
updateListing(listing, game),
|
|
);
|
|
|
|
if (!res.acknowledged || res.modifiedCount === 0) {
|
|
return [true, conflictResponse()];
|
|
}
|
|
|
|
return [false, singleResponse(game)];
|
|
};
|
|
|
|
return await retry(putItem);
|
|
};
|