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
use std::cmp::{Eq, PartialEq};
use std::hash::{Hash, Hasher};
use std::mem;

use doc::{Data, Document, Object, PrimaryData};
use error::Error;
use query::Query;
use sealed::Sealed;
use value::{Key, Map, Set, Value};
use view::Render;

/// Identifies an individual resource. Commonly found in an object's relationships.
///
/// Identifiers share their [equality] and [hashing] behavior with [`Object`]. For more
/// information, check out the *[resource identifier objects]* section of the
/// JSON API specification.
///
/// [`Object`]: ./struct.Object.html
/// [equality]: ./struct.Object.html#equality
/// [hashing]: ./struct.Object.html#hashing
/// [resource identifier objects]: https://goo.gl/vgfzru
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Identifier {
    /// A string that contains a unique identfier for this resource type (`kind`). For
    /// more information, check out the *[identification]* section of the JSON API
    /// specification.
    ///
    /// [identification]: https://goo.gl/3s681i
    pub id: String,

    /// Describes resources that share common attributes and relationships. This field is
    /// derived from the `type` field if the identifier is deserialized. For more
    /// information, check out the *[identification]* section of the JSON API
    /// specification.
    ///
    /// [identification]: https://goo.gl/3s681i
    #[serde(rename = "type")]
    pub kind: Key,

    /// Non-standard meta information. If this value of this field is empty, it will not
    /// be serialized. For more information, check out the *[meta information]* section
    /// of the JSON API specification.
    ///
    /// [meta information]: https://goo.gl/LyrGF8
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub meta: Map,

    /// Private field for backwards compatibility.
    #[serde(skip)]
    _ext: (),
}

impl Identifier {
    /// Returns a new `Identifier`.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate json_api;
    /// #
    /// # use json_api::Error;
    /// #
    /// # fn example() -> Result<(), Error> {
    /// use json_api::doc::Identifier;
    /// let mut ident = Identifier::new("users".parse()?, "1".to_owned());
    /// # Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// # example().unwrap();
    /// # }
    /// ```
    pub fn new(kind: Key, id: String) -> Self {
        Identifier {
            id,
            kind,
            meta: Default::default(),
            _ext: (),
        }
    }
}

impl Eq for Identifier {}

impl From<Object> for Identifier {
    fn from(object: Object) -> Self {
        let Object { id, kind, meta, .. } = object;
        let mut ident = Identifier::new(kind, id);

        ident.meta = meta;
        ident
    }
}

impl<'a> From<&'a Object> for Identifier {
    fn from(object: &'a Object) -> Self {
        object.clone().into()
    }
}

impl Hash for Identifier {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
        self.kind.hash(state);
    }
}

impl PartialEq for Identifier {
    fn eq(&self, rhs: &Identifier) -> bool {
        self.id == rhs.id && self.kind == rhs.kind
    }
}

impl PartialEq<Object> for Identifier {
    fn eq(&self, rhs: &Object) -> bool {
        self.id == rhs.id && self.kind == rhs.kind
    }
}

impl Render<Identifier> for Identifier {
    fn render(mut self, _: Option<&Query>) -> Result<Document<Identifier>, Error> {
        let meta = mem::replace(&mut self.meta, Default::default());

        Ok(Document::Ok {
            meta,
            data: Data::Member(Box::new(Some(self))),
            included: Default::default(),
            jsonapi: Default::default(),
            links: Default::default(),
        })
    }
}

impl Render<Identifier> for Vec<Identifier> {
    fn render(self, _: Option<&Query>) -> Result<Document<Identifier>, Error> {
        Ok(Document::Ok {
            data: Data::Collection(self),
            included: Default::default(),
            jsonapi: Default::default(),
            links: Default::default(),
            meta: Default::default(),
        })
    }
}

impl PrimaryData for Identifier {
    fn flatten(self, incl: &Set<Object>) -> Value {
        incl.into_iter()
            .find(|item| self == **item)
            .map(|item| item.clone().flatten(incl))
            .unwrap_or_default()
    }
}

impl Sealed for Identifier {}