summaryrefslogtreecommitdiff
path: root/dichroism/src/handlers.rs
blob: b4b117cddad8271d0c0be37335eb5491349f9923 (plain) (blame)
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
use crate::dtos::*;
use crate::repo;
use crate::types::DbPool;
use actix_web::{get, patch, post, web, Error, HttpResponse, Responder};

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hey, this is an API!")
}

#[get("/products")]
async fn get_products(pool: web::Data<DbPool>) -> Result<HttpResponse, Error> {
    let conn = pool.get().expect("Couldn't get DB connection from pool.");
    let products: Vec<Product> = web::block(move || repo::read_products(&conn))
        .await
        .map_err(|e| {
            eprintln!("{}", e);
            HttpResponse::InternalServerError().body(e.to_string())
        })?
        .into_iter()
        .map(|p| p.into())
        .collect();
    Ok(HttpResponse::Ok().json(products))
}

#[patch("/products/{id}")]
async fn update_product(
    _pool: web::Data<DbPool>,
    id: web::Path<u32>,
    updated_product: web::Json<ProductPatch>,
) -> Result<HttpResponse, Error> {
    dbg!(id, updated_product);
    Ok(HttpResponse::Ok().finish())
}

#[post("/products")]
async fn create_product(
    _pool: web::Data<DbPool>,
    new_product: web::Json<NewProduct>,
) -> Result<HttpResponse, Error> {
    dbg!(new_product);
    Ok(HttpResponse::Ok().finish())
}