|
|
@@ -1,10 +1,10 @@
|
|
|
use uuid::Uuid;
|
|
|
use chrono::{DateTime, Utc};
|
|
|
-use sqlx::PgPool;
|
|
|
+use sqlx::{PgPool, FromRow};
|
|
|
use serde::Serialize;
|
|
|
use crate::http_error::HttpError;
|
|
|
|
|
|
-#[derive(Serialize)]
|
|
|
+#[derive(Serialize, FromRow)]
|
|
|
pub struct Game {
|
|
|
pub id: Uuid,
|
|
|
pub user_id: Uuid,
|
|
|
@@ -26,7 +26,7 @@ impl Game {
|
|
|
|
|
|
pub async fn insert(&self, db: &PgPool) -> Result<(), HttpError> {
|
|
|
sqlx::query(
|
|
|
- "INSERT into games(id, user_id, title, game_context, created_at)
|
|
|
+ "INSERT INTO games(id, user_id, title, game_context, created_at)
|
|
|
VALUES($1, $2, $3, $4, $5)"
|
|
|
)
|
|
|
.bind(&self.id)
|
|
|
@@ -39,4 +39,22 @@ impl Game {
|
|
|
|
|
|
Ok(())
|
|
|
}
|
|
|
+
|
|
|
+ pub async fn get_one(db: &PgPool, id: Uuid, user_id: Option<Uuid>) -> Result<Game, HttpError> {
|
|
|
+ let result = sqlx::query_as::<_, Game>(
|
|
|
+ "SELECT *
|
|
|
+ FROM games
|
|
|
+ WHERE id = $1
|
|
|
+ AND ($2::uuid IS NULL OR user_id = $2)"
|
|
|
+ )
|
|
|
+ .bind(id)
|
|
|
+ .bind(user_id)
|
|
|
+ .fetch_optional(db)
|
|
|
+ .await?;
|
|
|
+
|
|
|
+ match result {
|
|
|
+ Some(g) => Ok(g),
|
|
|
+ None => Err(HttpError::NotFound("Game not found".into()))
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|