From 89b2507495dec2835de4b28ade8c05ac4534f937 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Sat, 10 Sep 2022 17:50:40 +0200 Subject: Perform `find_by_id` for models and author_id() --- src/models/model.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'src') diff --git a/src/models/model.rs b/src/models/model.rs index a87cddb..f31c057 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -2,6 +2,7 @@ use crate::config::PAGE_LIMIT; use crate::db::get_client; use crate::errors::AppError; +use serde_json::json; use sqlx::types::JsonValue; use chrono::{Local, NaiveDateTime}; @@ -112,6 +113,27 @@ impl Model { Ok(rec) } + /// Returns the model with id = `model_id` + pub async fn find_by_id(model_id: i32) -> Result { + let pool = unsafe { get_client() }; + + let rec = 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 + WHERE models.id = $1 + "#, + model_id + ) + .fetch_one(pool) + .await?; + + Ok(rec) + } + /// List all models pub async fn list(page: i64) -> Result, AppError> { let pool = unsafe { get_client() }; @@ -142,3 +164,12 @@ impl Model { Ok(row.count.unwrap()) } } + +impl ModelUser { + pub fn author_id(&self) -> JsonValue { + match &self.author { + Some(json) => json.get("id").unwrap().clone(), + None => json!(0), + } + } +} -- cgit v1.2.3-71-g8e6c