/*
* 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)
}