From 56e50564e87cc764fc5b815f19aa56560f78e4d3 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Mon, 12 Sep 2022 14:03:12 +0200 Subject: Keep saved filepath in the database --- src/models/model.rs | 41 +++++++++++++++++++++++++++++++++++++++++ src/routes/model.rs | 8 +++++--- 2 files changed, 46 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/models/model.rs b/src/models/model.rs index f31c057..0336c20 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -54,6 +54,14 @@ pub struct ModelUser { author: Option, } +#[derive(Deserialize, Serialize)] +pub struct ModelUpload { + id: i32, + model_id: i32, + filepath: String, + created: NaiveDateTime, +} + impl Model { pub fn new( name: String, @@ -173,3 +181,36 @@ impl ModelUser { } } } + +impl ModelUpload { + pub fn new(filepath: String, model_id: i32) -> Self { + let now = Local::now().naive_utc(); + Self { + id: 0, + filepath, + model_id, + created: now, + } + } + + /// Create a new upload for model + pub async fn create(file: ModelUpload) -> Result { + let pool = unsafe { get_client() }; + + let rec = sqlx::query_as!( + ModelUpload, + r#" + INSERT INTO uploads (filepath, model_id, created) + VALUES ( $1, $2, $3) + RETURNING * + "#, + file.filepath, + file.model_id, + file.created, + ) + .fetch_one(pool) + .await?; + + Ok(rec) + } +} diff --git a/src/routes/model.rs b/src/routes/model.rs index 3d5084c..f85e9a7 100644 --- a/src/routes/model.rs +++ b/src/routes/model.rs @@ -3,7 +3,7 @@ use crate::errors::AppError; use crate::files::upload; use crate::models::{ auth::Claims, - model::{Model, ModelCreate, ModelUser}, + model::{Model, ModelCreate, ModelUpload, ModelUser}, }; use crate::pagination::Pagination; use axum::{ @@ -61,7 +61,7 @@ async fn upload_model_file( claims: Claims, Path(model_id): Path, ContentLengthLimit(multipart): ContentLengthLimit, -) -> Result { +) -> Result, AppError> { let model = match Model::find_by_id(model_id).await { Ok(model) => model, Err(_) => { @@ -75,7 +75,9 @@ async fn upload_model_file( match upload(multipart, vec!["stl"]).await { Ok(saved_file) => { - return Ok(format!("Uploaded {}", saved_file)); + let model_file = ModelUpload::create(ModelUpload::new(saved_file, model_id)).await?; + + return Ok(Json(model_file)); } Err(e) => Err(e), } -- cgit v1.2.3-71-g8e6c