Skip to main content

server/services/action/
join_game.rs

1use crate::{
2    domain::{GameCommand, GameId, UserId},
3    error::{ServerError, bug},
4    server_state::ServerState,
5};
6
7/// Joins an existing game as a guest.
8///
9/// This function allows a user to join a game that has been hosted by another user.
10/// The game must have an available slot for a guest. After joining, the game state
11/// is updated accordingly.
12///
13/// # Parameters
14///
15/// - `server_state`: The shared server state containing the game and database.
16/// - `user_id`: The ID of the user who wants to join the game.
17/// - `game_id`: The ID of the game to join.
18///
19/// # Returns
20///
21/// Returns `Ok(())` if the user successfully joined the game.
22/// Returns a `ServerError` if the game is not found, the user is forbidden from joining,
23/// or another internal error occurs.
24pub async fn join_game(
25    server_state: ServerState,
26    user_id: UserId,
27    game_id: GameId,
28) -> Result<(), ServerError> {
29    let aggregate_id = game_id.value().to_string();
30
31    let command = GameCommand::JoinGame { user_id };
32
33    server_state
34        .cqrs
35        .execute(&aggregate_id, command)
36        .await
37        .map_err(bug!())?;
38
39    Ok(())
40}