summaryrefslogblamecommitdiff
path: root/dichroism/src/handlers.rs
blob: e4ea6a00bc910bbd2018274b7c0c8a9b5c108e15 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12



                          
                     
                                                                





                                                   











                                                                             
                  
                                                                                       















                                                                                             








                                                                               
 
use super::image_repo;
use super::product_repo;
use super::types::DbPool;
use crate::config::Config;
use crate::image_api;
use actix_web::{get, post, web, Error, HttpResponse, Responder};

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

#[get("/images")]
async fn get_images(pool: web::Data<DbPool>) -> Result<HttpResponse, Error> {
    let conn = pool.get().expect("Couldn't get DB connection from pool.");
    let images = web::block(move || image_repo::read_images(&conn))
        .await
        .map_err(|e| {
            eprintln!("{}", e);
            HttpResponse::InternalServerError().finish()
        })?;
    Ok(HttpResponse::Ok().json(images))
}

#[post("/images")]
async fn create_image(_config: web::Data<Config>, req_body: String) -> impl Responder {
    let data = match image_api::extract_data(&req_body) {
        Err(e) => return HttpResponse::BadRequest().body(format!("fail: {}", e.to_string())),
        Ok(d) => d,
    };

    if let Err(e) = image_api::generate_images(data) {
        return HttpResponse::BadRequest().body(format!(
            "Unable to extract image from data URI: {}",
            e.to_string()
        ));
    }

    HttpResponse::Ok().body("Image created.")
}

#[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 = web::block(move || product_repo::read_products(&conn))
        .await
        .map_err(|e| {
            eprintln!("{}", e);
            HttpResponse::InternalServerError().finish()
        })?;
    Ok(HttpResponse::Ok().json(products))
}