setup some race condition protection on update, host client now starts game when everyone is ready
This commit is contained in:
@ -15,6 +15,7 @@ import {
|
||||
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> => {
|
||||
@ -35,19 +36,35 @@ export const PUT: RequestHandler = async ({ params, request }): Promise<Response
|
||||
return badRequestResponse("malformed request");
|
||||
}
|
||||
|
||||
const listing = await readListingById(ServerCollections.Games, id, isListing<GameData>);
|
||||
if (!listing) {
|
||||
return notFoundResponse();
|
||||
}
|
||||
const putItem = async (): Promise<[boolean, Response]> => {
|
||||
const listing = await readListingById(
|
||||
ServerCollections.Games,
|
||||
id,
|
||||
isListing<GameData>,
|
||||
);
|
||||
|
||||
if (listing.data.isStarted === true) {
|
||||
return conflictResponse();
|
||||
}
|
||||
if (!listing) {
|
||||
return [false, notFoundResponse()];
|
||||
}
|
||||
|
||||
const game = Game.from(listing.data);
|
||||
if (game.setPlayerReady(player) === null) return notFoundResponse();
|
||||
if (listing.data.isStarted === true) {
|
||||
return [false, conflictResponse()];
|
||||
}
|
||||
|
||||
await writeUpdatedListing(ServerCollections.Games, updateListing(listing, game));
|
||||
const game = Game.from(listing.data);
|
||||
if (game.setPlayerReady(player) === null) return [false, notFoundResponse()];
|
||||
|
||||
return singleResponse(game);
|
||||
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);
|
||||
};
|
||||
|
Reference in New Issue
Block a user