framework_cqrs_lib/cqrs/infra/helpers/
http_response.rs1use actix_web::HttpResponse;
2use serde::de::DeserializeOwned;
3use serde::Serialize;
4
5use crate::cqrs::models::errors::{Error, ResultErr};
6
7pub enum HttpKindResponse {
8 Created,
9 Ok,
10}
11
12impl HttpKindResponse {
13 pub fn to_http_response<T>(&self, data: &T) -> HttpResponse
14 where
15 T: Serialize + DeserializeOwned,
16 {
17 match self {
18 HttpKindResponse::Created => HttpResponse::Created().json(data),
19 HttpKindResponse::Ok => HttpResponse::Ok().json(data),
20 }
21 }
22}
23
24impl<T> CanToHttpResponse<T> for ResultErr<T>
25where
26 T: Serialize + DeserializeOwned,
27{
28 fn to_http_response_with_error_mapping(&self, http_status: HttpKindResponse) -> HttpResponse {
29 match self {
30 Ok(k) => http_status.to_http_response(k),
31 Err(err) => {
32 match err {
33 Error::Http(http_error) => {
34 match http_error.status {
35 Some(400) => HttpResponse::BadRequest().json(err),
36 Some(404) => HttpResponse::NotFound().json(err),
37 _ => HttpResponse::InternalServerError().json(err)
38 }
39 }
40 Error::Simple(_) => HttpResponse::InternalServerError().json(err)
41 }
42 }
43 }
44 }
45}
46
47pub trait CanToHttpResponse<T> {
48 fn to_http_response_with_error_mapping(&self, http_status: HttpKindResponse) -> HttpResponse;
49}