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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use std::collections::btree_map::Entry;
use std::collections::*;
use std::vec::*;

use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use super::link::HalLink;
use super::{HalError, HalResult};
use serde_json::{from_value, to_value, Map, Value as JsonValue};

/// A Simple wrapper around a vector to allow custom
/// serialization when only 1 element is contained.
///
/// # example
///
/// In the example below, the vector serializes to json as an object if it contains
/// only one value, but as an array if more than one.
///
/// ```rust
/// # extern crate serde_json;
/// # extern crate rustic_hal;
/// use rustic_hal::resource::OneOrMany;
/// use rustic_hal::HalLink;
///
/// use serde_json::to_string;
/// # fn main() {
/// let mut v = OneOrMany::new();
/// v.push(&HalLink::new("http://test.com"));
///
/// assert_eq!(to_string(&v).unwrap(), r#"{"href":"http://test.com"}"#);
///
/// v.push(&HalLink::new("http://test2.com"));
///
/// assert_eq!(to_string(&v).unwrap(), r#"[{"href":"http://test.com"},{"href":"http://test2.com"}]"#);
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct OneOrMany<T> {
    force_many: bool,
    content: Vec<T>,
}

impl<T> OneOrMany<T>
where
    T: Sized + Clone,
{
    /// create a new empty object
    pub fn new() -> OneOrMany<T> {
        OneOrMany {
            content: Vec::new(),
            force_many: false,
        }
    }

    /// Force to be serialized as array, even if only one element
    pub fn force_many(mut self) -> Self {
        self.force_many = true;
        self
    }

    /// retrieve the length of the wrapped vector
    pub fn len(&self) -> usize {
        self.content.len()
    }

    pub fn is_empty(&self) -> bool {
        self.content.is_empty()
    }

    /// Retrieves a single element if possible.
    ///
    pub fn single(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            Some(&self.content[0])
        }
    }

    /// Returns an immutable reference to the
    /// contained links
    pub fn many(&self) -> &Vec<T> {
        &self.content
    }

    /// Add an element to the wrapped vector.
    pub fn push(&mut self, newval: &T) {
        self.content.push(newval.clone());
    }

    /// Adds an element to the vector in a chainable way
    pub fn with(mut self, newval: &T) -> Self {
        self.content.push(newval.clone());
        self
    }
}

impl<T> Serialize for OneOrMany<T>
where
    T: Serialize + Clone,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if self.is_empty() && !self.force_many {
            ().serialize(serializer)
        } else if self.len() == 1 && !self.force_many {
            self.single().serialize(serializer)
        } else {
            self.content.serialize(serializer)
        }
    }
}

impl<'de, T> Deserialize<'de> for OneOrMany<T>
where
    for<'d> T: Deserialize<'d> + Clone,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {


        let value: JsonValue = Deserialize::deserialize(deserializer)?;
        let v2 = value.clone();
        match v2 {
            JsonValue::Object(_) => {
                let obj: T = match from_value(value) {
                    Ok(v) => v,
                    Err(e) => return Err(D::Error::custom(format!("JSON Error: {:?}", e))),
                };
                let mut res = OneOrMany::new();
                res.push(&obj);
                Ok(res)
            }
            JsonValue::Array(_) => {
                let obj: Vec<T> = match from_value(value) {
                    Ok(v) => from_value(v).unwrap(),
                    Err(e) => return Err(D::Error::custom(format!("JSON Error: {:?}", e))),
                };
                let mut res = OneOrMany::new();
                res.content = obj;
                Ok(res)
            }
            _ => {
                let obj: T = match from_value(value) {
                    Ok(v) => v,
                    Err(e) => return Err(D::Error::custom(format!("JSON Error: {:?}", e)))
                };
                let mut res = OneOrMany::new();
                res.push(&obj);
                Ok(res)
            }
        }
    }
}

/// The HAL Resource structure.

#[derive(Clone, Serialize, Deserialize)]
pub struct HalResource {
    #[serde(rename = "_links", default, skip_serializing_if = "BTreeMap::is_empty")]
    /// Map of links to related resources.
    links: BTreeMap<String, OneOrMany<HalLink>>,

    #[serde(
        rename = "_embedded",
        default,
        skip_serializing_if = "BTreeMap::is_empty"
    )]
    /// Map of set of embedded resources.
    embedded: BTreeMap<String, OneOrMany<HalResource>>,

    #[serde(
        rename = "_curies",
        default,
        skip_serializing_if = "BTreeMap::is_empty"
    )]
    /// Documentations Curies
    curies: BTreeMap<String, HalLink>,

    #[serde(flatten)]
    /// The actual resource data
    data: Option<JsonValue>,
}

impl HalResource {
    pub fn new<T>(payload: T) -> HalResource
    where
        T: Serialize,
    {
        let val = match to_value(payload) {
            Ok(val) => match val {
                JsonValue::Object(_) => Some(val),
                _ => None,
            },
            _ => None,
        };

        HalResource {
            links: BTreeMap::new(),
            embedded: BTreeMap::new(),
            curies: BTreeMap::new(),
            data: val,
        }
    }

    pub fn with_link<S, L>(mut self, name: S, link: L) -> Self
    where
        S: Into<String>,
        L: Into<HalLink>,
    {
        let lk_name = name.into();
        match self.links.entry(lk_name.clone()) {
            Entry::Vacant(entry) => {
                let mut lk = OneOrMany::new();

                let mut lk = match lk_name.as_ref() {
                    "curies" => lk.force_many(),
                    _ => lk,
                };

                lk.push(&(link.into()));
                entry.insert(lk);
            }
            Entry::Occupied(mut entry) => {
                let mut content = entry.get_mut(); //&mut HalLinks
                content.push(&(link.into()));
            }
        }
        self
    }

    /// Retrieve one named link if found. Returns the first one if more than one.
    pub fn get_link(&self, name: &str) -> Option<&HalLink> {
        match self.links.get(name) {
            Some(link) => link.single(),
            None => None,
        }
    }

    /// Retrieve the self link
    pub fn get_self(&self) -> Option<&HalLink> {
        self.get_link("self")
    }

    /// Retrieve the list of links for a key
    pub fn get_links(&self, name: &str) -> Option<&Vec<HalLink>> {
        match self.links.get(name) {
            Some(link) => Some(link.many()),
            None => None,
        }
    }

    pub fn with_resource(mut self, name: &str, resource: HalResource) -> Self {
        match self.embedded.entry(name.to_string()) {
            Entry::Vacant(entry) => {
                let mut resources = OneOrMany::new();
                resources.push(&resource);
                entry.insert(resources);
            }
            Entry::Occupied(mut entry) => {
                let mut content = entry.get_mut(); //&mut HalLinks
                content.push(&resource);
            }
        }
        self
    }

    pub fn with_resources(mut self, name: &str, resources: Vec<HalResource>) -> Self {
        match self.embedded.entry(name.to_string()) {
            Entry::Vacant(entry) => {
                let mut _resources = OneOrMany::new().force_many();

                for resource in resources.iter() {
                    _resources.push(resource)
                }
                entry.insert(_resources);
            }
            Entry::Occupied(mut entry) => {
                let mut content = entry.get_mut(); //&mut HalLinks

                for resource in resources.iter() {
                    content.push(&resource);
                }
            }
        }
        self
    }

    pub fn with_curie(self, name: &str, href: &str) -> Self {
        self.with_link("curies", HalLink::new(href).templated(true).with_name(name))
    }

    pub fn with_extra_data<V>(mut self, name: &str, value: V) -> Self
    where
        V: Serialize,
    {
        match self.data {
            Some(JsonValue::Object(ref mut m)) => {
                m.insert(name.to_string(), to_value(value).unwrap());
            }
            _ => {
                let mut data = Map::<String, JsonValue>::new();
                data.insert(name.to_string(), to_value(value).unwrap());
                self.data = Some(JsonValue::Object(data));
            }
        };
        self
    }

    pub fn get_extra_data<V>(&self, name: &str) -> HalResult<V>
    where
        for<'de> V: Deserialize<'de>,
    {
        let data = match self.data {
            Some(JsonValue::Object(ref m)) => m,
            _ => return Err(HalError::Custom("Invalid payload".to_string())),
        };
        match data.get(name) {
            Some(v) => from_value::<V>(v.clone()).or_else(|e| Err(HalError::Json(e))),
            None => Err(HalError::Custom(format!("Key {} missing in payload", name))),
        }
    }

    pub fn get_data<V>(&self) -> HalResult<V>
    where
        for<'de> V: Deserialize<'de>,
    {
        match self.data {
            Some(ref val) => from_value::<V>(val.clone()).or_else(|e| Err(HalError::Json(e))),
            None => Err(HalError::Custom("No value".to_owned())),
        }
    }
}

impl PartialEq for HalResource {
    fn eq(&self, other: &HalResource) -> bool {
        self.get_self() == other.get_self()
    }
}