framework_cqrs_lib/cqrs/infra/mappers/
event_api_view.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
use std::collections::HashMap;

use serde::Serialize;

use crate::cqrs::core::context::Context;
use crate::cqrs::core::data::EntityEvent;
use crate::cqrs::models::jsonapi::CanBeView;
use crate::cqrs::models::views::{DataWrapperView, LinkView};
use crate::cqrs::models::views::command_handler_view::{ApiView, AttributesEvent, DataRS, DataWrapper, RelatedLinks, Relationships};

pub fn from_entity_event_to_view<DATA, VIEW>(
    event: EntityEvent<DATA, String>,
    ontology: String,
    complete_ontology: String,
    context: &Context,
) -> DataWrapperView<ApiView<VIEW>>
where
    VIEW: Serialize + Clone,
    DATA: Clone + CanBeView<VIEW>,
{
    let type_urn_event = format!("{complete_ontology}:event");
    let event_id = event.event_id;
    let state_id = event.entity_id;

    let external_url = context.meta
        .get("externalUrl")
        .map(|urlref| urlref.clone())
        .unwrap_or("unknown".to_string());

    DataWrapperView {
        data: ApiView {
            r#type: type_urn_event,
            id: event_id.clone(),
            attributes: AttributesEvent {
                attributes: event.data.to_view(),
            },
            relationships: Relationships {
                entity: DataWrapper {
                    data: DataRS {
                        r#type: complete_ontology,
                        id: state_id.clone(),
                    },
                    links: RelatedLinks {
                        related: format!("{external_url}/{ontology}/{state_id}")
                    },
                }
            },
            links: LinkView {
                links: HashMap::from([
                    (
                        "self".to_string(),
                        format!("{external_url}/{ontology}/{state_id}/events/{event_id}")
                    )
                ]),
            },
        }
    }
}