Switch from "impl Responder" to Result<> response
This commit is contained in:
parent
a17a9868fa
commit
09c50411d1
3 changed files with 99 additions and 133 deletions
|
@ -16,7 +16,7 @@ pub enum DatabaseError {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DatabaseError {
|
impl DatabaseError {
|
||||||
fn get_code(&self) -> StatusCode {
|
pub fn get_code(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
DatabaseError::NotFound => StatusCode::NOT_FOUND,
|
DatabaseError::NotFound => StatusCode::NOT_FOUND,
|
||||||
DatabaseError::Protected => StatusCode::FORBIDDEN,
|
DatabaseError::Protected => StatusCode::FORBIDDEN,
|
||||||
|
|
|
@ -1,24 +1,28 @@
|
||||||
|
use crate::db::errors::DatabaseError;
|
||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use actix_web::HttpResponse;
|
use actix_web::HttpResponse;
|
||||||
use serde::ser::SerializeStruct;
|
use serde::ser::SerializeStruct;
|
||||||
use serde::{Serialize, Serializer};
|
use serde::{Serialize, Serializer};
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum HandlerError {
|
pub enum ApiError {
|
||||||
BadUid,
|
BadUid,
|
||||||
ProtectedSchedule,
|
ProtectedSchedule,
|
||||||
|
DatabaseError(DatabaseError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HandlerError {
|
impl ApiError {
|
||||||
fn get_code(&self) -> StatusCode {
|
fn get_code(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
HandlerError::BadUid => StatusCode::BAD_REQUEST,
|
ApiError::BadUid => StatusCode::BAD_REQUEST,
|
||||||
HandlerError::ProtectedSchedule => StatusCode::FORBIDDEN,
|
ApiError::ProtectedSchedule => StatusCode::FORBIDDEN,
|
||||||
|
ApiError::DatabaseError(db_error) => db_error.get_code(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for HandlerError {
|
impl Serialize for ApiError {
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where
|
where
|
||||||
S: Serializer,
|
S: Serializer,
|
||||||
|
@ -30,17 +34,46 @@ impl Serialize for HandlerError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&HandlerError> for String {
|
impl From<&ApiError> for String {
|
||||||
fn from(err: &HandlerError) -> Self {
|
fn from(err: &ApiError) -> Self {
|
||||||
match err {
|
match err {
|
||||||
HandlerError::BadUid => String::from("the uid is in a bad format"),
|
ApiError::BadUid => String::from("the uid is in a bad format"),
|
||||||
HandlerError::ProtectedSchedule => String::from("the targeted schedule is protected"),
|
ApiError::ProtectedSchedule => String::from("the targeted schedule is protected"),
|
||||||
|
ApiError::DatabaseError(db_err) => String::from(db_err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<HandlerError> for HttpResponse {
|
impl From<&ApiError> for HttpResponse {
|
||||||
fn from(err: HandlerError) -> Self {
|
fn from(err: &ApiError) -> Self {
|
||||||
HttpResponse::build(err.get_code()).json(err)
|
HttpResponse::build(err.get_code()).json(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Display for ApiError {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}: {}", self.get_code(), String::from(self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl actix_web::error::ResponseError for ApiError {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
self.get_code()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_response(&self) -> HttpResponse {
|
||||||
|
HttpResponse::from(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<sqlx::Error> for ApiError {
|
||||||
|
fn from(err: sqlx::Error) -> Self {
|
||||||
|
ApiError::DatabaseError(DatabaseError::from(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<DatabaseError> for ApiError {
|
||||||
|
fn from(err: DatabaseError) -> Self {
|
||||||
|
ApiError::DatabaseError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
use actix_web::{delete, get, post, put, web, HttpResponse, Responder};
|
use actix_web::{delete, get, post, put, web, HttpResponse};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sqlx::pool::PoolConnection;
|
use sqlx::pool::PoolConnection;
|
||||||
use sqlx::{Pool, Sqlite};
|
use sqlx::{Pool, Sqlite};
|
||||||
|
@ -10,7 +10,7 @@ use crate::db::errors::DatabaseError;
|
||||||
use crate::db::models::{Periods, Schedule};
|
use crate::db::models::{Periods, Schedule};
|
||||||
use crate::db::schedules::*;
|
use crate::db::schedules::*;
|
||||||
use crate::db::tag::get_tag;
|
use crate::db::tag::get_tag;
|
||||||
use crate::handlers::errors::HandlerError;
|
use crate::handlers::errors::ApiError;
|
||||||
use crate::return_models::ReturnSchedule;
|
use crate::return_models::ReturnSchedule;
|
||||||
use crate::types::EmgauwaUid;
|
use crate::types::EmgauwaUid;
|
||||||
use crate::utils::vec_has_error;
|
use crate::utils::vec_has_error;
|
||||||
|
@ -23,19 +23,10 @@ pub struct RequestSchedule {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/api/v1/schedules")]
|
#[get("/api/v1/schedules")]
|
||||||
pub async fn index(pool: web::Data<Pool<Sqlite>>) -> impl Responder {
|
pub async fn index(pool: web::Data<Pool<Sqlite>>) -> Result<HttpResponse, ApiError> {
|
||||||
let pool_conn = pool.acquire().await;
|
let mut pool_conn = pool.acquire().await?;
|
||||||
if let Err(err) = pool_conn {
|
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
|
||||||
}
|
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let schedules = get_schedules(&mut pool_conn).await;
|
let schedules = get_schedules(&mut pool_conn).await?;
|
||||||
|
|
||||||
if let Err(err) = schedules {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let schedules = schedules.unwrap();
|
|
||||||
|
|
||||||
let mut return_schedules: Vec<ReturnSchedule> =
|
let mut return_schedules: Vec<ReturnSchedule> =
|
||||||
schedules.iter().map(ReturnSchedule::from).collect();
|
schedules.iter().map(ReturnSchedule::from).collect();
|
||||||
|
@ -43,91 +34,60 @@ pub async fn index(pool: web::Data<Pool<Sqlite>>) -> impl Responder {
|
||||||
schedule.load_tags(&mut pool_conn);
|
schedule.load_tags(&mut pool_conn);
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpResponse::Ok().json(return_schedules)
|
Ok(HttpResponse::Ok().json(return_schedules))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/api/v1/schedules/tag/{tag}")]
|
#[get("/api/v1/schedules/tag/{tag}")]
|
||||||
pub async fn tagged(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
|
pub async fn tagged(
|
||||||
let pool_conn = pool.acquire().await;
|
pool: web::Data<Pool<Sqlite>>,
|
||||||
if let Err(err) = pool_conn {
|
path: web::Path<(String,)>,
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
) -> Result<HttpResponse, ApiError> {
|
||||||
}
|
let mut pool_conn = pool.acquire().await?;
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let (tag,) = path.into_inner();
|
let (tag,) = path.into_inner();
|
||||||
let tag_db = get_tag(&mut pool_conn, &tag).await;
|
let tag_db = get_tag(&mut pool_conn, &tag).await?;
|
||||||
if let Err(err) = tag_db {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let tag_db = tag_db.unwrap();
|
|
||||||
|
|
||||||
let schedules = get_schedules_by_tag(&mut pool_conn, &tag_db).await;
|
let schedules = get_schedules_by_tag(&mut pool_conn, &tag_db).await?;
|
||||||
if let Err(err) = schedules {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let schedules = schedules.unwrap();
|
|
||||||
|
|
||||||
let mut return_schedules: Vec<ReturnSchedule> =
|
let mut return_schedules: Vec<ReturnSchedule> =
|
||||||
schedules.iter().map(ReturnSchedule::from).collect();
|
schedules.iter().map(ReturnSchedule::from).collect();
|
||||||
for schedule in return_schedules.iter_mut() {
|
for schedule in return_schedules.iter_mut() {
|
||||||
schedule.load_tags(&mut pool_conn);
|
schedule.load_tags(&mut pool_conn);
|
||||||
}
|
}
|
||||||
HttpResponse::Ok().json(return_schedules)
|
Ok(HttpResponse::Ok().json(return_schedules))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/api/v1/schedules/{schedule_id}")]
|
#[get("/api/v1/schedules/{schedule_id}")]
|
||||||
pub async fn show(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
|
pub async fn show(
|
||||||
let pool_conn = pool.acquire().await;
|
pool: web::Data<Pool<Sqlite>>,
|
||||||
if let Err(err) = pool_conn {
|
path: web::Path<(String,)>,
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
) -> Result<HttpResponse, ApiError> {
|
||||||
}
|
let mut pool_conn = pool.acquire().await?;
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let (schedule_uid,) = path.into_inner();
|
let (schedule_uid,) = path.into_inner();
|
||||||
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
|
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;
|
||||||
|
|
||||||
match emgauwa_uid {
|
let schedule = get_schedule_by_uid(&mut pool_conn, &emgauwa_uid).await?;
|
||||||
Ok(uid) => {
|
|
||||||
let schedule = get_schedule_by_uid(&mut pool_conn, &uid).await;
|
let mut return_schedule = ReturnSchedule::from(schedule);
|
||||||
match schedule {
|
|
||||||
Ok(ok) => {
|
|
||||||
let mut return_schedule = ReturnSchedule::from(ok);
|
|
||||||
return_schedule.load_tags(&mut pool_conn);
|
return_schedule.load_tags(&mut pool_conn);
|
||||||
HttpResponse::Ok().json(return_schedule)
|
Ok(HttpResponse::Ok().json(return_schedule))
|
||||||
}
|
|
||||||
Err(err) => HttpResponse::from(err),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => HttpResponse::from(err),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/api/v1/schedules")]
|
#[post("/api/v1/schedules")]
|
||||||
pub async fn add(
|
pub async fn add(
|
||||||
pool: web::Data<Pool<Sqlite>>,
|
pool: web::Data<Pool<Sqlite>>,
|
||||||
data: web::Json<RequestSchedule>,
|
data: web::Json<RequestSchedule>,
|
||||||
) -> impl Responder {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
let pool_conn = pool.acquire().await;
|
let mut pool_conn = pool.acquire().await?;
|
||||||
if let Err(err) = pool_conn {
|
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
|
||||||
}
|
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let new_schedule = create_schedule(&mut pool_conn, &data.name, &data.periods).await;
|
let new_schedule = create_schedule(&mut pool_conn, &data.name, &data.periods).await?;
|
||||||
|
|
||||||
if let Err(err) = new_schedule {
|
set_schedule_tags(&mut pool_conn, &new_schedule, data.tags.as_slice()).await?;
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let new_schedule = new_schedule.unwrap();
|
|
||||||
|
|
||||||
let result = set_schedule_tags(&mut pool_conn, &new_schedule, data.tags.as_slice()).await;
|
|
||||||
if let Err(err) = result {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut return_schedule = ReturnSchedule::from(new_schedule);
|
let mut return_schedule = ReturnSchedule::from(new_schedule);
|
||||||
return_schedule.load_tags(&mut pool_conn);
|
return_schedule.load_tags(&mut pool_conn);
|
||||||
HttpResponse::Created().json(return_schedule)
|
Ok(HttpResponse::Created().json(return_schedule))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn add_list_single(
|
async fn add_list_single(
|
||||||
|
@ -146,12 +106,8 @@ async fn add_list_single(
|
||||||
pub async fn add_list(
|
pub async fn add_list(
|
||||||
pool: web::Data<Pool<Sqlite>>,
|
pool: web::Data<Pool<Sqlite>>,
|
||||||
data: web::Json<Vec<RequestSchedule>>,
|
data: web::Json<Vec<RequestSchedule>>,
|
||||||
) -> impl Responder {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
let pool_conn = pool.acquire().await;
|
let mut pool_conn = pool.acquire().await?;
|
||||||
if let Err(err) = pool_conn {
|
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
|
||||||
}
|
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let result: Vec<Result<Schedule, DatabaseError>> = data
|
let result: Vec<Result<Schedule, DatabaseError>> = data
|
||||||
.as_slice()
|
.as_slice()
|
||||||
|
@ -162,13 +118,13 @@ pub async fn add_list(
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
match vec_has_error(&result) {
|
match vec_has_error(&result) {
|
||||||
true => HttpResponse::from(
|
true => Ok(HttpResponse::from(
|
||||||
result
|
result
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|r| r.is_err())
|
.find(|r| r.is_err())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.unwrap_err(),
|
.unwrap_err(),
|
||||||
),
|
)),
|
||||||
false => {
|
false => {
|
||||||
let mut return_schedules: Vec<ReturnSchedule> = result
|
let mut return_schedules: Vec<ReturnSchedule> = result
|
||||||
.iter()
|
.iter()
|
||||||
|
@ -178,7 +134,7 @@ pub async fn add_list(
|
||||||
for schedule in return_schedules.iter_mut() {
|
for schedule in return_schedules.iter_mut() {
|
||||||
schedule.load_tags(&mut pool_conn);
|
schedule.load_tags(&mut pool_conn);
|
||||||
}
|
}
|
||||||
HttpResponse::Created().json(return_schedules)
|
Ok(HttpResponse::Created().json(return_schedules))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -188,25 +144,13 @@ pub async fn update(
|
||||||
pool: web::Data<Pool<Sqlite>>,
|
pool: web::Data<Pool<Sqlite>>,
|
||||||
path: web::Path<(String,)>,
|
path: web::Path<(String,)>,
|
||||||
data: web::Json<RequestSchedule>,
|
data: web::Json<RequestSchedule>,
|
||||||
) -> impl Responder {
|
) -> Result<HttpResponse, ApiError> {
|
||||||
let pool_conn = pool.acquire().await;
|
let mut pool_conn = pool.acquire().await?;
|
||||||
if let Err(err) = pool_conn {
|
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
|
||||||
}
|
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let (schedule_uid,) = path.into_inner();
|
let (schedule_uid,) = path.into_inner();
|
||||||
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
|
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;
|
||||||
if let Err(err) = emgauwa_uid {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let emgauwa_uid = emgauwa_uid.unwrap();
|
|
||||||
|
|
||||||
let schedule = get_schedule_by_uid(&mut pool_conn, &emgauwa_uid).await;
|
let schedule = get_schedule_by_uid(&mut pool_conn, &emgauwa_uid).await?;
|
||||||
if let Err(err) = schedule {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let schedule = schedule.unwrap();
|
|
||||||
|
|
||||||
let schedule = update_schedule(
|
let schedule = update_schedule(
|
||||||
&mut pool_conn,
|
&mut pool_conn,
|
||||||
|
@ -214,42 +158,31 @@ pub async fn update(
|
||||||
data.name.as_str(),
|
data.name.as_str(),
|
||||||
data.periods.borrow(),
|
data.periods.borrow(),
|
||||||
)
|
)
|
||||||
.await;
|
.await?;
|
||||||
if let Err(err) = schedule {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
let schedule = schedule.unwrap();
|
|
||||||
|
|
||||||
let result = set_schedule_tags(&mut pool_conn, &schedule, data.tags.as_slice()).await;
|
set_schedule_tags(&mut pool_conn, &schedule, data.tags.as_slice()).await?;
|
||||||
if let Err(err) = result {
|
|
||||||
return HttpResponse::from(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut return_schedule = ReturnSchedule::from(schedule);
|
let mut return_schedule = ReturnSchedule::from(schedule);
|
||||||
return_schedule.load_tags(&mut pool_conn);
|
return_schedule.load_tags(&mut pool_conn);
|
||||||
HttpResponse::Ok().json(return_schedule)
|
Ok(HttpResponse::Ok().json(return_schedule))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[delete("/api/v1/schedules/{schedule_id}")]
|
#[delete("/api/v1/schedules/{schedule_id}")]
|
||||||
pub async fn delete(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
|
pub async fn delete(
|
||||||
let pool_conn = pool.acquire().await;
|
pool: web::Data<Pool<Sqlite>>,
|
||||||
if let Err(err) = pool_conn {
|
path: web::Path<(String,)>,
|
||||||
return HttpResponse::from(DatabaseError::from(err));
|
) -> Result<HttpResponse, ApiError> {
|
||||||
}
|
let mut pool_conn = pool.acquire().await?;
|
||||||
let mut pool_conn = pool_conn.unwrap();
|
|
||||||
|
|
||||||
let (schedule_uid,) = path.into_inner();
|
let (schedule_uid,) = path.into_inner();
|
||||||
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
|
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;
|
||||||
|
|
||||||
match emgauwa_uid {
|
match emgauwa_uid {
|
||||||
Ok(uid) => match uid {
|
EmgauwaUid::Off => Err(ApiError::ProtectedSchedule),
|
||||||
EmgauwaUid::Off => HttpResponse::from(HandlerError::ProtectedSchedule),
|
EmgauwaUid::On => Err(ApiError::ProtectedSchedule),
|
||||||
EmgauwaUid::On => HttpResponse::from(HandlerError::ProtectedSchedule),
|
EmgauwaUid::Any(_) => {
|
||||||
EmgauwaUid::Any(_) => match delete_schedule_by_uid(&mut pool_conn, uid).await {
|
delete_schedule_by_uid(&mut pool_conn, emgauwa_uid).await?;
|
||||||
Ok(_) => HttpResponse::Ok().json("schedule got deleted"),
|
Ok(HttpResponse::Ok().json("schedule got deleted"))
|
||||||
Err(err) => HttpResponse::from(err),
|
}
|
||||||
},
|
|
||||||
},
|
|
||||||
Err(err) => HttpResponse::from(err),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue