diff options
| -rw-r--r-- | migrations/20220912114912_add-models-uploads-table.sql | 6 | ||||
| -rw-r--r-- | src/models/model.rs | 41 | ||||
| -rw-r--r-- | src/routes/model.rs | 8 |
3 files changed, 52 insertions, 3 deletions
diff --git a/migrations/20220912114912_add-models-uploads-table.sql b/migrations/20220912114912_add-models-uploads-table.sql new file mode 100644 index 0000000..6647c69 --- /dev/null +++ b/migrations/20220912114912_add-models-uploads-table.sql @@ -0,0 +1,6 @@ +CREATE TABLE uploads ( + id SERIAL PRIMARY KEY, + model_id INTEGER REFERENCES models(id) NOT NULL, + filepath VARCHAR NOT NULL, + created TIMESTAMP NOT NULL +); 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<JsonValue>, } +#[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<ModelUpload, AppError> { + 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<i32>, ContentLengthLimit(multipart): ContentLengthLimit<Multipart, { MAX_UPLOAD_FILE_SIZE }>, -) -> Result<String, AppError> { +) -> Result<Json<ModelUpload>, 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), } |
