aboutsummaryrefslogtreecommitdiff
path: root/src/handlers/product.rs
blob: 60a4684e71094b366dfe3872c015995cb61a07cb (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::models::{NewProduct, Product};
use crate::schema::product::dsl::*;
use crate::TPool;

use actix_web::{web, HttpResponse, Responder};
use diesel::prelude::*;
use log::{error, info};
use serde::Deserialize;

pub async fn new_product(
    pool: web::Data<TPool>,
    item: web::Json<NewProduct>,
) -> impl Responder {
    info!("New product hit: {:?}", item.name);
    let conn = pool.get().unwrap();
    diesel::insert_into(product)
        .values(item.into_inner())
        .execute(&conn)
        .expect("Coundn't connect to DB");
    HttpResponse::Ok().body("Inserted successfully!")
}

pub async fn product_details(
    pool: web::Data<TPool>,
    product_id: web::Path<i32>,
) -> impl Responder {
    let conn = pool.get().unwrap();
    let product_id = product_id.into_inner();
    info!("Fetching product details for {}", product_id);
    let selected_product = product
        .filter(id.eq(&product_id))
        .limit(1)
        .first::<Product>(&conn);
    match selected_product {
        Ok(m) => {
            info!("Found product: {}", product_id);
            HttpResponse::Ok().json(m)
        }
        Err(_) => {
            error!("Product not found: {}", product_id);
            HttpResponse::NotFound().finish()
        }
    }
}

#[derive(Deserialize)]
pub struct UpdateProduct {
    name: String,
    kind: Option<String>,
    price: f32,
    description: Option<String>,
}

pub async fn update_product(
    pool: web::Data<TPool>,
    product_id: web::Path<i32>,
    product_details: web::Json<UpdateProduct>,
) -> impl Responder {
    let conn = pool.get().unwrap();
    let product_id = product_id.into_inner();
    let product_details = product_details.into_inner();
    info!("Updating product: {:?}", product_id);
    match diesel::update(product.filter(id.eq(product_id)))
        .set((
            name.eq(product_details.name),
            kind.eq(product_details.kind),
            price.eq(product_details.price),
            description.eq(product_details.description),
        ))
        .execute(&conn)
    {
        Ok(_) => {
            return HttpResponse::Ok().body("Changed product successfully")
        }
        _ => {
            return HttpResponse::InternalServerError()
                .body("Unable to update record")
        }
    }
}