/*
* 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::{ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};
use laurelin_shared::error::api::APIError;
use uuid::Uuid;
use crate::{
models::{Game, GameData, InsertableGame, InsertableGameData},
schema::{gamedata, games},
};
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: 0,
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)
}