DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 87f3f31d9d46d0ac597b7c6d58c1b5c36d21aa1a deck-builder/api/src/actions/game/create.rs -rw-r--r-- 1.4 KiB
87f3f31dJonni Liljamo feat(schema, shared, api): move all types to shared, separate schema 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * This file is part of laurelin/api
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use diesel::{PgConnection, RunQueryDsl};
use laurelin_schema::schema::{gamedata, games};
use laurelin_shared::{
    error::api::APIError,
    types::game::{Game, GameData, InsertableGame, InsertableGameData, GAMESTATE_FORMING},
};
use uuid::Uuid;

pub(crate) fn create(conn: &mut PgConnection, user_id: &str) -> Result<Game, APIError> {
    let new_gamedata = InsertableGameData {
        turn: 0,
        host_hand: None,
        host_deck: None,
        guest_hand: None,
        guest_deck: None,
    };

    let gamedata: GameData = match diesel::insert_into(gamedata::table)
        .values(&new_gamedata)
        .get_result::<GameData>(conn)
    {
        Err(_) => return Err(APIError::Undefined), // TODO: new error variant
        Ok(gamedata) => gamedata,
    };

    let new_game = InsertableGame {
        // TODO: handle unwrap
        host_id: Uuid::parse_str(user_id).unwrap(),
        guest_id: None,
        state: GAMESTATE_FORMING,
        ended_at: None,
        game_data_id: gamedata.id,
    };

    let game: Game = match diesel::insert_into(games::table)
        .values(&new_game)
        .get_result::<Game>(conn)
    {
        Err(_) => return Err(APIError::Undefined), // TODO: new error variant
        Ok(game) => game,
    };

    Ok(game)
}