summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2022-09-10 15:50:40 +0000
committerSanto Cariotti <santo@dcariotti.me>2022-09-10 15:50:40 +0000
commit89b2507495dec2835de4b28ade8c05ac4534f937 (patch)
tree3ba329b35ae0ec62974ace6b78032a0fd55f4ae0 /src
parent1666d757b87578eed22b4e1c67420c602554295a (diff)
Perform `find_by_id` for models and author_id()
Diffstat (limited to 'src')
-rw-r--r--src/models/model.rs31
1 files changed, 31 insertions, 0 deletions
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<ModelUser, AppError> {
+ 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<Vec<ModelUser>, 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),
+ }
+ }
+}