framework_cqrs_lib/cqrs/infra/helpers/
context.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
50
51
52
53
54
55
56
57
58
59
use std::collections::HashMap;

use actix_web::HttpRequest;

use crate::cqrs::infra::helpers::header_value::CanSanitizeHeader;
use crate::cqrs::core::context::Context;

impl CanDecoreFromHttpRequest for Context {
    fn decore_with_http_header(&self, req: &HttpRequest) -> Self {
        let maybe_proto = req.headers()
            .get("X-Forwarded-Proto")
            .map(|header_value| header_value.clone().sanitize_header("X-Forwarded-Proto".to_string()))
            .map(|x| x.map(|x| Some(x)).unwrap_or(None))
            .flatten();

        let maybe_host = req.headers()
            .get("X-Forwarded-Host")
            .map(|header_value| header_value.clone().sanitize_header("X-Forwarded-Host".to_string()))
            .map(|x| x.map(|x| Some(x)).unwrap_or(None))
            .flatten();

        let maybe_prefix = req.headers()
            .get("X-Forwarded-Prefix")
            .map(|header_value| header_value.clone().sanitize_header("X-Forwarded-Prefix".to_string()))
            .map(|x| x.map(|x| Some(x)).unwrap_or(None))
            .flatten();

        let maybe_external_url = match (maybe_proto.clone(), maybe_host.clone(), maybe_prefix.clone()) {
            (Some(proto), Some(host), Some(prefix)) =>
                Some(format!("{}://{}{}", proto.1, host.1, prefix.1)),
            (Some(proto), Some(host), None) =>
                Some(format!("{}://{}", proto.1, host.1)),
            _ => None
        }.map(|val| ("externalUrl".to_string(), val));

        let meta = vec![maybe_proto, maybe_host, maybe_prefix, maybe_external_url]
            .iter()
            .fold(HashMap::new(), |acc, current| {
                match current {
                    Some((key, value)) => acc
                        .into_iter()
                        .chain(HashMap::from([(key.clone(), value.clone())]))
                        .collect::<HashMap<String, String>>(),

                    None => acc
                }
            });


        Context {
            meta,
            ..self.clone()
        }
    }
}

pub trait CanDecoreFromHttpRequest: Sized {
    fn decore_with_http_header(&self, req: &HttpRequest) -> Self;
}