From e8c799cb65f58c1e9a4b2809489ef3b5760638d8 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Fri, 9 Sep 2022 11:31:25 +0200 Subject: Serialize author' info for models --- src/models/model.rs | 31 +++++++++++++++++++++++++++---- src/routes/model.rs | 4 ++-- 2 files changed, 29 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/models/model.rs b/src/models/model.rs index 1fe9b61..e3fc7ac 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -1,5 +1,6 @@ use crate::db::get_client; use crate::errors::AppError; +use sqlx::types::JsonValue; use chrono::{Local, NaiveDateTime}; use serde::{Deserialize, Serialize}; @@ -34,6 +35,22 @@ pub struct ModelCreate { pub material: Option, } +#[derive(Serialize)] +pub struct ModelUser { + id: i32, + name: String, + description: Option, + duration: i32, + height: i32, + weight: i32, + printer: Option, + material: Option, + author_id: i32, + created: NaiveDateTime, + updated: NaiveDateTime, + author: Option, +} + impl Model { pub fn new( name: String, @@ -94,11 +111,17 @@ impl Model { } /// List all models - pub async fn list() -> Result, AppError> { + pub async fn list() -> Result, AppError> { let pool = unsafe { get_client() }; - let rows = sqlx::query_as!(Model, r#"SELECT * FROM models"#) - .fetch_all(pool) - .await?; + let rows = sqlx::query_as!( + ModelUser, + r#"SELECT + models.*, + json_build_object('id', users.id, 'email', users.email, 'username', users.username, 'is_staff', users.is_staff) as author + FROM models JOIN users ON users.id = models.author_id"# + ) + .fetch_all(pool) + .await?; Ok(rows) } diff --git a/src/routes/model.rs b/src/routes/model.rs index b1d4cc2..a5cd2b3 100644 --- a/src/routes/model.rs +++ b/src/routes/model.rs @@ -1,7 +1,7 @@ use crate::errors::AppError; use crate::models::{ auth::Claims, - model::{Model, ModelCreate}, + model::{Model, ModelCreate, ModelUser}, }; use axum::{routing::get, Json, Router}; @@ -11,7 +11,7 @@ pub fn create_route() -> Router { } /// List models. -async fn list_models() -> Result>, AppError> { +async fn list_models() -> Result>, AppError> { let models = Model::list().await?; Ok(Json(models)) -- cgit v1.2.3-71-g8e6c