framework_cqrs_lib/cqrs/infra/helpers/
http_response.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use actix_web::HttpResponse;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::cqrs::models::errors::{Error, ResultErr};

pub enum HttpKindResponse {
    Created,
    Ok,
}

impl HttpKindResponse {
    pub fn to_http_response<T>(&self, data: &T) -> HttpResponse
    where
        T: Serialize + DeserializeOwned,
    {
        match self {
            HttpKindResponse::Created => HttpResponse::Created().json(data),
            HttpKindResponse::Ok => HttpResponse::Ok().json(data),
        }
    }
}

impl<T> CanToHttpResponse<T> for ResultErr<T>
where
    T: Serialize + DeserializeOwned,
{
    fn to_http_response_with_error_mapping(&self, http_status: HttpKindResponse) -> HttpResponse {
        match self {
            Ok(k) => http_status.to_http_response(k),
            Err(err) => {
                match err {
                    Error::Http(http_error) => {
                        match http_error.status {
                            Some(400) => HttpResponse::BadRequest().json(err),
                            Some(404) => HttpResponse::NotFound().json(err),
                            _ => HttpResponse::InternalServerError().json(err)
                        }
                    }
                    Error::Simple(_) => HttpResponse::InternalServerError().json(err)
                }
            }
        }
    }
}

pub trait CanToHttpResponse<T> {
    fn to_http_response_with_error_mapping(&self, http_status: HttpKindResponse) -> HttpResponse;
}