Skip to content

Commit

Permalink
add endpoint to resign game early
Browse files Browse the repository at this point in the history
  • Loading branch information
Artemis21 committed Feb 14, 2024
1 parent fab2e5e commit 1f375ea
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/game/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ use serde::{Deserialize, Serialize};

/// Collect API routes for managing games.
pub fn routes() -> Vec<rocket::Route> {
routes![new_game, recent_games, get_game, new_guess, get_clip,]
routes![
new_game,
recent_games,
get_game,
resign_game,
new_guess,
get_clip,
]
}

impl Session {
Expand Down Expand Up @@ -115,6 +122,23 @@ struct NewGuess {
track_id: Option<deezer::Id>,
}

/// Resign from the given game.
#[post("/games/<id>/resign")]
async fn resign_game(
mut tx: Transaction<'_>,
auth: Session,
id: i32,
) -> Result<Json<game::Response>, ApiError> {
let mut game = auth.game(&mut tx, id).await?;
if game.is_over() {
return Err(ApiError::conflict("game is already over"));
}
game.set_won(&mut tx, false).await?;
let game = game.into_response(&mut tx).await?;
tx.commit().await?;
Ok(Json(game))
}

/// Submit a guess for the authenticated user's active game.
#[post("/games/<id>/guesses", data = "<body>")]
async fn new_guess(
Expand Down
15 changes: 15 additions & 0 deletions web/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,21 @@ export function useNewGame() {
return useMutate(() => "/games", newGame, { populateCache: false });
}

/** Resign from a game.
*
* @param gameId The ID of the game to resign from.
* @returns The updated game.
*/
async function resignGame({ gameId }: { gameId: number }): Promise<Game> {
const response = await endpoint("POST", `/games/${gameId}/resign`);
return await response.json();
}

export function useResignGame() {
const key = ({ gameId }: { gameId: number }) => ["/games/:id", gameId];
return useMutate(key, resignGame, { populateCache: true });
}

/** Guess a track.
*
* @param gameId The ID of the game to submit a guess for.
Expand Down

0 comments on commit 1f375ea

Please sign in to comment.