user.rs 2.22 KB
use crate::models::user::{self, Action};
use crate::AppData;

use actix_web::{Error, HttpResponse, web};
use anyhow::Result;

pub async fn create_user( app_data: web::Data<AppData>
                        , item: web::Json<user::UserJson> )
    -> Result<HttpResponse, Error>
{
    let pool = app_data.database_pool.clone();
    let item = item.into_inner();

    Ok(web::block(move || user::create_user(pool, item))
       . await
       . map(|action| {
           match action {
               Action::Created(user) => HttpResponse::Created().json(user),
               Action::Found(user)   => HttpResponse::Ok().json(user),
           }})
       . map_err(|_| HttpResponse::InternalServerError())?)
}

pub async fn get_users(app_data: web::Data<AppData>)
    -> Result<HttpResponse, Error>
{
    let pool = app_data.database_pool.clone();

    Ok(web::block(move || user::get_users(pool))
       . await
       . map(|users| HttpResponse::Ok().json(users))
       . map_err(|_| HttpResponse::InternalServerError())?)
}

pub async fn get_user(app_data: web::Data<AppData>, id: web::Path<i32>)
    -> Result<HttpResponse, Error>
{
    let pool = app_data.database_pool.clone();
    let id   = id.into_inner();

    Ok(web::block(move || user::get_user(pool, id))
       . await
       . map(|user| HttpResponse::Ok().json(user))
       . map_err(|_| HttpResponse::InternalServerError())?)
}

pub async fn delete_user(app_data: web::Data<AppData>, id: web::Path<i32>)
    -> Result<HttpResponse, Error>
{
    let pool = app_data.database_pool.clone();
    let id   = id.into_inner();

    Ok(web::block(move || user::delete_user(pool, id))
       . await
       . map(|_| HttpResponse::NoContent().finish())
       . map_err(|_| HttpResponse::InternalServerError())?)
}

pub async fn update_user( app_data: web::Data<AppData>
                        , id:   web::Path<i32>
                        , item: web::Json<user::UserJson> )
    -> Result<HttpResponse, Error>
{
    let pool = app_data.database_pool.clone();
    let id   = id.into_inner();
    let item = item.into_inner();

    Ok(web::block(move || user::update_user(pool, id, item))
       . await
       . map(|user| HttpResponse::Ok().json(user))
       . map_err(|_| HttpResponse::InternalServerError())?)
}