31 lines
857 B
Rust

use actix_web::{web, HttpResponse, Responder};
use garde::Validate;
use sqlx::PgPool;
use crate::{
endpoints::clothing::{NewOrEditClothingForm, ReadClothingPartialTemplate},
models::{Clothing, Role, User},
utils::{ApplicationError, TemplateResponse},
};
#[actix_web::post("/clothing")]
pub async fn post(
user: web::ReqData<User>,
pool: web::Data<PgPool>,
form: web::Form<NewOrEditClothingForm>,
) -> Result<impl Responder, ApplicationError> {
if user.role != Role::Admin {
return Err(ApplicationError::Unauthorized);
}
if let Err(e) = form.validate() {
return Ok(HttpResponse::UnprocessableEntity().body(e.to_string()));
};
let clothing = Clothing::create(pool.get_ref(), &form.name).await?;
let template = ReadClothingPartialTemplate { c: clothing };
Ok(template.to_response()?)
}