routes.rs 2.48 KB
use crate::models::{self, Action};
use crate::Pool;

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

pub async fn root() -> Result<actix_files::NamedFile, Error> {
    Ok(actix_files::NamedFile::open("static/index.html")?)
}

pub async fn p404() -> Result<actix_files::NamedFile, Error> {
    Ok(actix_files::NamedFile::open("static/404.html")?)
}

pub async fn favicon() -> Result<actix_files::NamedFile, Error> {
    Ok(actix_files::NamedFile::open("static/favicon.ico")?)
}

pub async fn create_user( pool: web::Data<Pool>
                        , item: web::Json<models::UserJson> )
    -> Result<HttpResponse, Error>
{
    let pool = pool.into_inner();
    let item = item.into_inner();

    Ok(web::block(move || models::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(pool: web::Data<Pool>)
    -> Result<HttpResponse, Error>
{
    Ok(web::block(move || models::get_users(pool.into_inner()))
       . await
       . map(|users| HttpResponse::Ok().json(users))
       . map_err(|_| HttpResponse::InternalServerError())?)
}

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

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

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

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

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

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