core_lib/errors/
metadata.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq)]
pub struct Metadata {
    metadata: HashMap<String, Value>,
}

impl Metadata {
    pub fn new() -> Self {
        Metadata {
            metadata: HashMap::new(),
        }
    }

    pub fn with<K, V>(key: K, value: V) -> Self
    where
        K: Into<String>,
        V: Serialize,
    {
        Metadata::new().and(key, value)
    }
    pub fn and<K, V>(mut self, key: K, value: V) -> Self
    where
        K: Into<String>,
        V: Serialize,
    {
        if let Ok(value) = serde_json::to_value(value) {
            self.metadata.insert(key.into(), value);
        }

        self
    }

    pub fn merge(mut self, other: Metadata) -> Self {
        self.metadata.extend(other.metadata);
        self
    }

    pub fn values(&self) -> &HashMap<String, Value> {
        &self.metadata
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use serde_json::json;

    #[derive(Serialize)]
    struct Data {
        msg: String,
    }

    #[test]
    fn metadata() {
        let m = Metadata::with("prop1", "hello world")
            .and("prop2", 123)
            .and(
                "prop3",
                Data {
                    msg: "Hello World".to_string(),
                },
            );

        assert_eq!(
            m.values().get("prop1").unwrap(),
            &Value::String("hello world".to_string())
        );
        assert_eq!(m.values().get("prop2").unwrap(), &json!(123));
        assert_eq!(
            m.values().get("prop3").unwrap(),
            &json!(Data {
                msg: "Hello World".to_string()
            })
        );
    }
}