trifid/trifid-api/src/response.rs

49 lines
1.3 KiB
Rust
Raw Normal View History

2023-08-19 03:55:27 +00:00
use std::fmt::{Display, Formatter};
use actix_web::{HttpRequest, HttpResponse, Responder, ResponseError};
use actix_web::body::EitherBody;
use actix_web::web::Json;
use log::error;
use sea_orm::DbErr;
2023-08-19 03:58:00 +00:00
2023-08-19 03:55:27 +00:00
use crate::error::{APIError, APIErrorsResponse};
pub struct OkResponse<T: Responder>(T);
#[derive(Debug)]
pub struct ErrResponse(APIErrorsResponse);
impl<T: Responder> Responder for OkResponse<T> {
type Body = T::Body;
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> {
self.0.respond_to(req)
}
}
impl Responder for ErrResponse {
type Body = EitherBody<String>;
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> {
Json(self.0).respond_to(req)
}
}
impl From<DbErr> for ErrResponse {
fn from(value: DbErr) -> Self {
error!("database error: {}", value);
2023-08-19 03:58:00 +00:00
Self(APIErrorsResponse { errors: vec![
2023-08-19 03:55:27 +00:00
APIError {
code: "ERR_DB_ERROR".to_string(),
message: "There was an error performing the database query. Please try again later.".to_string(),
path: None,
}
2023-08-19 03:58:00 +00:00
] })
2023-08-19 03:55:27 +00:00
}
}
impl Display for ErrResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl ResponseError for ErrResponse {}