Add delete handler and json-payload error response

This commit is contained in:
Tobias Reisinger 2021-11-08 13:11:20 +01:00
parent e6278176e4
commit 7254eddc6c
8 changed files with 162 additions and 51 deletions
src/handlers/v1

View file

@ -1,7 +1,6 @@
use std::str::FromStr;
use actix_web::{HttpResponse, Responder, web, get};
use std::convert::TryFrom;
use actix_web::{HttpResponse, Responder, web, get, delete};
use serde::{Serialize, Deserialize};
use uuid::Uuid;
use crate::db;
use crate::db::models::Periods;
@ -22,26 +21,18 @@ pub async fn index() -> impl Responder {
#[get("/api/v1/schedules/{schedule_id}")]
pub async fn show(web::Path((schedule_uid,)): web::Path<(String,)>) -> impl Responder {
let emgauwa_uid = match schedule_uid.as_str() {
"on" => Ok(EmgauwaUid::On),
"off" => Ok(EmgauwaUid::Off),
any => match Uuid::from_str(any) {
Ok(uuid) => Ok(EmgauwaUid::Any(uuid)),
Err(_) => Err(HandlerError::BadUidError)
}
};
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
match emgauwa_uid {
Ok(uid) => {
let schedule = db::get_schedule_by_uid(uid);
match schedule {
Ok(ok) => HttpResponse::Ok().json(ok),
Err(err) => HttpResponse::NotFound().json(err),
Err(err) => HttpResponse::from(err),
}
},
Err(err) => HttpResponse::BadRequest().json(err)
Err(err) => HttpResponse::from(err)
}
}
pub async fn add(post: web::Json<RequestSchedule>) -> impl Responder {
@ -49,10 +40,25 @@ pub async fn add(post: web::Json<RequestSchedule>) -> impl Responder {
match new_schedule {
Ok(ok) => HttpResponse::Created().json(ok),
Err(err) => HttpResponse::InternalServerError().json(err),
Err(err) => HttpResponse::from(err),
}
}
pub async fn delete() -> impl Responder {
"hello from delete schedule"
#[delete("/api/v1/schedules/{schedule_id}")]
pub async fn delete(web::Path((schedule_uid,)): web::Path<(String,)>) -> impl Responder {
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
match emgauwa_uid {
Ok(uid) => match uid {
EmgauwaUid::Off => HttpResponse::from(HandlerError::ProtectedSchedule),
EmgauwaUid::On => HttpResponse::from(HandlerError::ProtectedSchedule),
EmgauwaUid::Any(_) => {
match db::delete_schedule_by_uid(uid) {
Ok(_) => HttpResponse::Ok().json("schedule got deleted"),
Err(err) => HttpResponse::from(err)
}
}
},
Err(err) => HttpResponse::from(err)
}
}