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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use crate::{Meta, Relationships, Links, ResourceObject, Attributes, Identifier};
use serde::{Serialize as SerializeTrait, de::DeserializeOwned};
use serde_derive::{Serialize, Deserialize}; 
use serde_json::{self, Value};
use std::collections::BTreeMap;

/// A generic resource object of some unknown type
///
/// Should never be directly manipulated, convert to/from `ResourceObject` or 
/// `Identifier` instead
///
/// See the [JSON:API docs](https://jsonapi.org/format/#document-resource-objects)
/// for more information
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct GenericObject {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub (crate) id: Option<String>,
   #[serde(rename = "type")]
    pub (crate) kind: String,
    // This should maybe be a serde_json::Map to make converting faster
    // Alternately convert with a custom deserializer but also no,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub (crate) attributes: Option<BTreeMap<String, Value>>, 
    #[serde(skip_serializing_if = "Option::is_none")]
    pub (crate) relationships: Option<Relationships>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub (crate) links: Option<Links>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub (crate) meta: Option<Meta>,
}

impl GenericObject {
    /// Returns the type of the object (renamed here to `kind` due to keyword restrictuons)
    pub fn kind<'a>(&'a self) -> &'a str {
        &self.kind
    }
}

impl<A> From<ResourceObject<A>> for GenericObject
where A: Attributes + SerializeTrait + DeserializeOwned {
    fn from(ro: ResourceObject<A>) -> Self {
        let v = serde_json::to_value(&ro.attributes).unwrap();
        Self {
            id: ro.id,
            kind: A::kind(),
            attributes: serde_json::from_value(v).unwrap(),
            relationships: ro.relationships,
            links: ro.links,
            meta: ro.meta,
        }
    }
}

impl<A> From<&ResourceObject<A>> for GenericObject 
where A: Attributes + SerializeTrait + DeserializeOwned {
    fn from(ro: &ResourceObject<A>) -> Self {
        let v = serde_json::to_value(&ro.attributes).unwrap();
        Self {
            id: ro.id.clone(),
            kind: A::kind(),
            attributes: serde_json::from_value(v).unwrap(),
            relationships: ro.relationships.clone(),
            links: ro.links.clone(),
            meta: ro.meta.clone(),
        }
    }
}

impl From<Identifier> for GenericObject {
    fn from(id: Identifier) -> Self {
        Self {
            id: Some(id.id),
            kind: id.kind,
            attributes: None,
            relationships: None,
            links: None,
            meta: id.meta,
        }
    }
}

impl From<&Identifier> for GenericObject {
    fn from(id: &Identifier) -> Self {
        Self {
            id: Some(id.id.clone()),
            kind: id.kind.clone(),
            attributes: None,
            relationships: None,
            links: None,
            meta: id.meta.clone(),
        }
    }
}

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

    #[test]
    fn serde_empty() {
        let g1 = GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: None,
            relationships: None,
            links: None,
            meta: None,
        };
        let s = serde_json::to_string(&g1).unwrap();
        assert_eq!(s, "{\"id\":\"a\",\"type\":\"b\"}");
        let g2 = serde_json::from_str(&s).unwrap();
        assert_eq!(g1, g2);
    }

    #[test]
    fn serde_full() {
        let g1 = GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: Some(BTreeMap::new()),
            relationships: Some(Relationships::new()),
            links: Some(Links::new()),
            meta: Some(Meta::new()),
        };
        let s = serde_json::to_string(&g1).unwrap();
        assert_eq!(s, "{\"id\":\"a\",\"type\":\"b\",\"attributes\":{},\"relationships\":{},\"links\":{},\"meta\":{}}");
        let g2 = serde_json::from_str(&s).unwrap();
        assert_eq!(g1, g2);
    }

    #[test]
    fn from_ro() {
        #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
        struct Attr {
            kitty: bool,
        };
        impl Attributes for Attr {
            fn kind() -> String { "b".into() }
        }

        let mut ro = ResourceObject::<Attr>::new("a".into(), None);
        let go = (&ro).into();
        assert_eq!(GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: None, 
            relationships: None,
            links: None,
            meta: None,
        }, go);

        let go = ro.clone().into();
        assert_eq!(GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: None, 
            relationships: None,
            links: None,
            meta: None,
        }, go);

        ro.attributes = Some(Attr{ kitty: true });
        ro.relationships = Some(Relationships::new());
        ro.links = Some(Links::new());
        ro.meta = Some(Meta::new());

        let mut attr = BTreeMap::new();
        attr.insert("kitty".into(), Value::Bool(true));

        let go = (&ro).into();
        assert_eq!(GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: Some(attr.clone()), 
            relationships: Some(Relationships::new()),
            links: Some(Links::new()),
            meta: Some(Meta::new()),
        }, go);

        let go = ro.into();
        assert_eq!(GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: Some(attr.clone()), 
            relationships: Some(Relationships::new()),
            links: Some(Links::new()),
            meta: Some(Meta::new()),
        }, go);
    }

    #[test]
    fn from_id() {
        let id = Identifier {
            id: "a".into(),
            kind: "b".into(),
            meta: Some(Meta::new()),
        };

        let go = (&id).into();
        assert_eq!(GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: None,
            relationships: None, 
            links: None,
            meta: Some(Meta::new()),
        }, go);

        let go = id.into();
        assert_eq!(GenericObject {
            id: Some("a".into()),
            kind: "b".into(),
            attributes: None,
            relationships: None, 
            links: None,
            meta: Some(Meta::new()),
        }, go);
    }
}