summaryrefslogtreecommitdiffstats
path: root/src/routes/model.rs
blob: 4ac268877e2838fa74dd7636d404989d42827f92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use crate::errors::AppError;
use crate::models::{
    auth::Claims,
    model::{Model, ModelCreate, ModelUser},
};
use crate::pagination::Pagination;
use axum::{extract::Query, routing::get, Json, Router};
use serde::Serialize;

/// Create routes for `/v1/models/` namespace
pub fn create_route() -> Router {
    Router::new().route("/", get(list_models).post(create_model))
}

#[derive(Serialize)]
struct ModelPagination {
    count: i64,
    results: Vec<ModelUser>,
}

/// List models.
async fn list_models(pagination: Query<Pagination>) -> Result<Json<ModelPagination>, AppError> {
    let page = pagination.0.page.unwrap_or_default();
    let results = Model::list(page).await?;
    let count = Model::count().await?;

    Ok(Json(ModelPagination { count, results }))
}

/// Create a model. Checks Authorization token
async fn create_model(
    Json(payload): Json<ModelCreate>,
    claims: Claims,
) -> Result<Json<Model>, AppError> {
    let model = Model::new(
        payload.name,
        payload.description,
        payload.duration,
        payload.height,
        payload.weight,
        payload.printer,
        payload.material,
        claims.user_id,
    );

    let model_new = Model::create(model).await?;

    Ok(Json(model_new))
}