Skip to main content

crossref_async/response/
mod.rs

1use crate::query::Visibility;
2use crate::response::work::*;
3use serde::de::Deserializer;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use std::collections::HashMap;
7use std::fmt;
8
9/// provides the types for a work response
10pub mod work;
11
12pub use crate::response::work::{Work, WorkList};
13
14/// Represents the whole crossref response for a any request.
15#[derive(Debug, Clone, Serialize)]
16#[serde(rename_all = "kebab-case")]
17pub struct Response {
18    /// the status of the request
19    pub status: String,
20    /// the type of the response message holds
21    pub message_type: MessageType,
22    /// the version of the service created this message
23    #[serde(default = "default_msg_version")]
24    pub message_version: String,
25    /// the actual message of the response
26    pub message: Option<Message>,
27}
28
29/// at some routes the `msg_version` is missing, this returns the default version for a crossref response
30fn default_msg_version() -> String {
31    "1.0.0".to_string()
32}
33
34/// this macro helps to generate a function that checks whether the message is of a specific type
35macro_rules! impl_msg_helper {
36    (single: $($name:ident -> $ident:ident,)*) => {
37    $(
38        /// checks if the message holds the variant
39        pub fn $name(&self) -> bool {
40           matches!(&self.message, Some(Message::$ident(_)))
41        }
42    )+
43    };
44}
45
46impl Response {
47    impl_msg_helper!(single:
48        is_work_ageny -> WorkAgency,
49        is_funder -> Funder,
50        is_prefix -> Prefix,
51        is_work -> Work,
52        is_type -> Type,
53        is_journal -> Journal,
54        is_member -> Member,
55        is_validation_failure -> ValidationFailure,
56        is_type_list -> TypeList,
57        is_work_list -> WorkList,
58        is_member_list -> MemberList,
59        is_journal_list -> JournalList,
60        is_funder_list -> FunderList,
61    );
62
63    /// checks whether the `message` holds a variant of `RouteNotFound`
64    pub fn is_route_not_found(&self) -> bool {
65        matches!(&self.message, Some(Message::RouteNotFound))
66    }
67}
68
69impl<'de> Deserialize<'de> for Response {
70    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71    where
72        D: Deserializer<'de>,
73    {
74        #[derive(Deserialize)]
75        #[serde(rename_all = "kebab-case")]
76        struct ResponseFragment {
77            status: String,
78            message_type: MessageType,
79            #[serde(default = "default_msg_version")]
80            message_version: String,
81            message: Option<Value>,
82        }
83
84        #[derive(Deserialize)]
85        #[serde(rename_all = "kebab-case")]
86        struct ListResp {
87            #[serde(default)]
88            facets: FacetMap,
89            next_cursor: Option<String>,
90            total_results: usize,
91            items_per_page: Option<usize>,
92            query: Option<QueryResponse>,
93            items: Value,
94        }
95
96        let fragment = ResponseFragment::deserialize(deserializer)?;
97
98        macro_rules! msg_arm {
99            ($ident:ident, $value:expr) => {{
100                Message::$ident(
101                    ::serde_json::from_value($value).map_err(::serde::de::Error::custom)?,
102                )
103            }};
104            ($ident:ident, $value:expr, $ty:ty) => {{
105                let list_resp: ListResp =
106                    ::serde_json::from_value($value).map_err(::serde::de::Error::custom)?;
107                let items: Vec<$ty> = ::serde_json::from_value(list_resp.items)
108                    .map_err(::serde::de::Error::custom)?;
109                Message::$ident($ident {
110                    facets: list_resp.facets,
111                    total_results: list_resp.total_results,
112                    items_per_page: list_resp.items_per_page,
113                    query: list_resp.query,
114                    items,
115                })
116            }};
117        }
118
119        fn work_list(msg: Value) -> Result<Message, serde_json::Error> {
120            let list_resp: ListResp = ::serde_json::from_value(msg)?;
121            let items: Vec<Work> = ::serde_json::from_value(list_resp.items)?;
122
123            Ok(Message::WorkList(WorkList {
124                facets: list_resp.facets,
125                total_results: list_resp.total_results,
126                items_per_page: list_resp.items_per_page,
127                query: list_resp.query,
128                items,
129                next_cursor: list_resp.next_cursor,
130            }))
131        }
132
133        let message = match fragment.message {
134            Some(msg) => Some(match &fragment.message_type {
135                MessageType::ValidationFailure => msg_arm!(ValidationFailure, msg),
136                MessageType::WorkAgency => msg_arm!(WorkAgency, msg),
137                MessageType::Prefix => msg_arm!(Prefix, msg),
138                MessageType::Type => msg_arm!(Type, msg),
139                MessageType::TypeList => msg_arm!(TypeList, msg, CrossrefType),
140                MessageType::Work => msg_arm!(Work, msg),
141                MessageType::WorkList => work_list(msg).map_err(::serde::de::Error::custom)?,
142                MessageType::Member => msg_arm!(Member, msg),
143                MessageType::MemberList => msg_arm!(MemberList, msg, Member),
144                MessageType::Journal => msg_arm!(Journal, msg),
145                MessageType::JournalList => msg_arm!(JournalList, msg, Journal),
146                MessageType::Funder => msg_arm!(Funder, msg),
147                MessageType::FunderList => msg_arm!(FunderList, msg, Funder),
148                MessageType::RouteNotFound => Message::RouteNotFound,
149            }),
150            _ => None,
151        };
152        Ok(Response {
153            status: fragment.status,
154            message_type: fragment.message_type,
155            message_version: fragment.message_version,
156            message,
157        })
158    }
159}
160
161macro_rules! impl_list_response {
162    ($($name:ident<$ty:ty>,)*) => {
163    $(
164        #[derive(Debug, Clone, Deserialize, Serialize)]
165        #[serde(rename_all = "kebab-case")]
166        #[allow(missing_docs)]
167        pub struct $name {
168             /// if facets where part in the request they are also included in the response
169            #[serde(default)]
170            pub facets: FacetMap,
171            /// the number of items that match the response
172            pub total_results: usize,
173            /// crossref responses for large number of items are divided in pages, number of elements to expect in `items`
174            pub items_per_page: Option<usize>,
175            /// if a query was set in the request, this will also be part in the response
176            pub query: Option<QueryResponse>,
177            /// all actual message items of the response
178            pub items: Vec<$ty>,
179        }
180    )+
181    };
182}
183impl_list_response!(
184    TypeList<CrossrefType>,
185    MemberList<Member>,
186    JournalList<Journal>,
187    FunderList<Funder>,
188);
189
190/// the different payloads of a response
191#[derive(Debug, Clone, Deserialize, Serialize)]
192#[serde(untagged)]
193pub enum Message {
194    /// if a request failed on the server side
195    ValidationFailure(Vec<Failure>),
196    /// a route could not be found on the server side
197    RouteNotFound,
198    /// the agency for a specific work
199    WorkAgency(WorkAgency),
200    /// metadata data for the DOI owner prefix
201    Prefix(Prefix),
202    /// a valid work type
203    Type(CrossrefType),
204    /// a list of valid work types
205    TypeList(TypeList),
206    /// a publication(journal, articles...)
207    Work(Box<Work>),
208    /// a list of publications
209    WorkList(WorkList),
210    /// a crossref member (mostly publishers)
211    Member(Box<Member>),
212    /// a list of crossref members
213    MemberList(MemberList),
214    /// a Journal publication
215    Journal(Box<Journal>),
216    /// list of journal publications
217    JournalList(JournalList),
218    /// a funder in the [funder registry](https://github.com/Crossref/open-funder-registry)
219    Funder(Box<Funder>),
220    /// a list of funder
221    FunderList(FunderList),
222}
223
224#[derive(Debug, Clone, Deserialize, Serialize)]
225#[allow(missing_docs)]
226pub struct CrossrefType {
227    pub id: String,
228    /// Name of work's publisher
229    pub label: String,
230}
231
232impl From<crate::query::types::Type> for CrossrefType {
233    fn from(t: crate::query::types::Type) -> CrossrefType {
234        CrossrefType {
235            id: t.id().to_string(),
236            label: t.label().to_string(),
237        }
238    }
239}
240
241/// response item for the `/works/{id}/agency` route
242#[derive(Debug, Clone, Deserialize, Serialize)]
243pub struct WorkAgency {
244    /// the DOI fo the work that belongs to the `agency`
245    #[serde(rename = "DOI")]
246    doi: String,
247    /// the agency that owns the work with `doi`
248    agency: Agency,
249}
250
251/// response item for the `/prefix/{id}/` route
252#[derive(Debug, Clone, Deserialize, Serialize)]
253#[allow(missing_docs)]
254pub struct Prefix {
255    pub member: String,
256    pub name: String,
257    pub prefix: String,
258}
259
260/// all possible `message-type` of a response
261#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
262#[serde(rename_all = "kebab-case")]
263#[allow(missing_docs)]
264pub enum MessageType {
265    WorkAgency,
266    Funder,
267    Prefix,
268    Member,
269    Work,
270    WorkList,
271    FunderList,
272    Type,
273    TypeList,
274    MemberList,
275    Journal,
276    JournalList,
277    ValidationFailure,
278    RouteNotFound,
279}
280
281impl MessageType {
282    /// the type identifier for a message
283    pub fn as_str(&self) -> &str {
284        match self {
285            MessageType::WorkAgency => "work-agency",
286            MessageType::Funder => "funder",
287            MessageType::Prefix => "prefix",
288            MessageType::Member => "member",
289            MessageType::MemberList => "member-list",
290            MessageType::Work => "work",
291            MessageType::WorkList => "work-list",
292            MessageType::FunderList => "funder-list",
293            MessageType::Type => "type",
294            MessageType::TypeList => "type-list",
295            MessageType::Journal => "journal",
296            MessageType::JournalList => "journal-list",
297            MessageType::ValidationFailure => "validation-failure",
298            MessageType::RouteNotFound => "route-not-found",
299        }
300    }
301}
302
303impl fmt::Display for MessageType {
304    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
305        self.as_str().fmt(f)
306    }
307}
308
309/// if a query was set in the request then it is also part of the result
310#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
311#[serde(rename_all = "kebab-case")]
312pub struct QueryResponse {
313    /// from which the returned items start
314    pub start_index: usize,
315    /// the terms that were initially set in the request query
316    pub search_terms: Option<String>,
317}
318
319// TODO impl CrossrefRoute for QueryResponse
320
321/// facets are returned as map
322pub type FacetMap = HashMap<String, FacetItem>;
323
324/// if a `facet` was set in a request `FacetMap` will be  in a `List` response as additional field of the message
325#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
326#[serde(rename_all = "kebab-case")]
327pub struct FacetItem {
328    /// represents the length of `values`
329    pub value_count: usize,
330    /// contains the
331    pub values: HashMap<String, usize>,
332}
333
334/// response item if a request could be processed
335#[derive(Debug, Clone, Deserialize, Serialize)]
336#[serde(rename_all = "kebab-case")]
337pub struct Failure {
338    /// identifier for a failue like `parameter-not-found`
339    #[serde(rename = "type")]
340    type_: String,
341    /// value that caused the failure
342    value: String,
343    /// the message from the server
344    message: String,
345}
346
347/// response item for the `/funder/{id}` route
348#[derive(Debug, Clone, Default, Deserialize, Serialize)]
349#[serde(rename_all = "kebab-case", default)]
350#[allow(missing_docs)]
351pub struct Funder {
352    pub hierarchy_names: HashMap<String, Option<String>>,
353    pub hierarchy: HashMap<String, HashMap<String, HashMap<String, bool>>>,
354    pub id: String,
355    pub location: String,
356    pub work_count: Option<usize>,
357    pub descendant_work_count: Option<usize>,
358    pub descendants: Vec<String>,
359    pub name: String,
360    pub alt_names: Vec<String>,
361    pub uri: String,
362    pub replaces: Vec<String>,
363    pub replaced_by: Vec<String>,
364    pub tokens: Vec<String>,
365}
366
367/// response item for the `/member/{id}` route
368#[derive(Debug, Clone, Default, Deserialize, Serialize)]
369#[serde(rename_all = "kebab-case", default)]
370#[allow(missing_docs)]
371pub struct Member {
372    pub primary_name: String,
373    pub last_status_check_time: usize,
374    pub counts: Counts,
375    pub breakdowns: Breakdowns,
376    pub prefixes: Vec<String>,
377    pub coverage: Coverage,
378    pub prefix: Vec<RefPrefix>,
379    pub id: usize,
380    pub tokens: Vec<String>,
381    pub counts_type: HashMap<String, HashMap<String, usize>>,
382    pub coverage_type: Value,
383    pub flags: HashMap<String, bool>,
384    pub location: String,
385    pub names: Vec<String>,
386}
387
388#[derive(Debug, Clone, Default, Deserialize, Serialize)]
389#[serde(rename_all = "kebab-case", default)]
390#[allow(missing_docs)]
391pub struct Counts {
392    pub total_dois: usize,
393    pub current_dois: usize,
394    pub backfile_dois: usize,
395}
396
397#[derive(Debug, Clone, Default, Deserialize, Serialize)]
398#[serde(rename_all = "kebab-case", default)]
399#[allow(missing_docs)]
400pub struct Breakdowns {
401    pub dois_by_issued_year: Vec<Vec<u32>>,
402}
403
404#[derive(Debug, Clone, Default, Deserialize, Serialize)]
405#[serde(rename_all = "kebab-case", default)]
406#[allow(missing_docs)]
407pub struct Coverage {
408    pub affiliations_current: f32,
409    pub similarity_checking_current: f32,
410    pub funders_backfile: f32,
411    pub licenses_backfile: f32,
412    pub funders_current: f32,
413    pub affiliations_backfile: f32,
414    pub resource_links_backfile: f32,
415    pub orcids_backfile: f32,
416    pub update_policies_current: f32,
417    pub open_references_backfile: f32,
418    pub orcids_current: f32,
419    pub similarity_checking_backfile: f32,
420    pub references_backfile: f32,
421    pub award_numbers_backfile: f32,
422    pub update_policies_backfile: f32,
423    pub licenses_current: f32,
424    pub award_numbers_current: f32,
425    pub abstracts_backfile: f32,
426    pub resource_links_current: f32,
427    pub abstracts_current: f32,
428    pub open_references_current: f32,
429    pub references_current: f32,
430}
431
432#[derive(Debug, Clone, Default, Deserialize, Serialize)]
433#[serde(rename_all = "kebab-case", default)]
434#[allow(missing_docs)]
435pub struct RefPrefix {
436    pub value: String,
437    pub name: String,
438    pub public_references: bool,
439    pub reference_visibility: Option<Visibility>,
440}
441
442/// response item for the `/journal/{id}` route
443#[derive(Debug, Clone, Deserialize, Serialize)]
444#[serde(rename_all = "kebab-case")]
445#[allow(missing_docs)]
446pub struct Journal {
447    /// could not determine type, possible PartialDateParts
448    pub last_status_check_time: Option<Value>,
449    pub counts: Option<usize>,
450    pub breakdowns: Option<Value>,
451    pub publisher: Option<String>,
452    pub coverage: Option<Value>,
453    pub title: Option<String>,
454    pub subjects: Vec<Value>,
455    pub coverage_type: Option<Value>,
456    pub flags: Option<Value>,
457    #[serde(rename = "ISSN")]
458    pub issn: Vec<String>,
459    pub issn_type: Vec<String>,
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use serde_json::*;
466
467    #[test]
468    fn facets_deserialize() {
469        let facets = r#"{
470      "affiliation": {
471        "value-count": 5,
472        "values": {
473          "of": 177247,
474          "university": 147649,
475          "department": 128741,
476          "and": 102652,
477          "medicine": 96232
478        }
479      },
480      "orcid": {
481        "value-count": 10,
482        "values": {
483          "http:\/\/orcid.org\/0000-0002-0270-1711": 67
484        }
485      }
486    }"#;
487
488        let _: FacetMap = from_str(facets).unwrap();
489    }
490
491    #[test]
492    fn agency_msg_deserialize() {
493        let agency_str = r#"{"status":"ok","message-type":"work-agency","message-version":"1.0.0","message":{"DOI":"10.1037\/0003-066x.59.1.29","agency":{"id":"crossref","label":"Crossref"}}}"#;
494
495        let agency: Response = from_str(agency_str).unwrap();
496
497        assert!(agency.is_work_ageny());
498    }
499
500    #[test]
501    fn funder_list_msg_deserialize() {
502        let funders_str = r#"{"status":"ok","message-type":"funder-list","message-version":"1.0.0","message":{"items-per-page":2,"query":{"start-index":0,"search-terms":"NSF"},"total-results":9,"items":[{ "id": "501100004190",
503  "location": "Norway",
504  "name": "Norsk  Sykepleierforbund",
505  "alt-names": [
506    "NSF"
507  ],
508  "uri": "http:\/\/dx.doi.org\/10.13039\/501100004190",
509  "replaces": [],
510  "replaced-by": [],
511  "tokens": [
512    "norsk"
513  ]
514}]}}"#;
515
516        let funders: Response = from_str(funders_str).unwrap();
517
518        assert!(funders.is_funder_list());
519    }
520
521    #[test]
522    fn funder_msg_deserialize() {
523        let funder_str = r#"{"status":"ok","message-type":"funder","message-version":"1.0.0","message":{ "id": "501100004190",
524  "location": "Norway",
525  "name": "Norsk  Sykepleierforbund",
526  "alt-names": [
527    "NSF"
528  ],
529  "uri": "http:\/\/dx.doi.org\/10.13039\/501100004190",
530  "replaces": [],
531  "replaced-by": [],
532  "tokens": [
533    "norsk"
534  ],
535  "work-count": 43,
536  "descendants": [],
537  "hierarchy-names": {
538    "100000019": "National Hemophilia Foundation"
539  },
540  "descendant-work-count": 43,
541    "hierarchy": {
542      "100000019": {}
543  }
544}}"#;
545
546        let funder: Response = from_str(funder_str).unwrap();
547
548        assert!(funder.is_funder());
549    }
550
551    #[test]
552    fn funder_msg_deserialize2() {
553        let funder_str = r#"{"status":"ok","message-type":"funder","message-version":"1.0.0","message":{"hierarchy-names":{"100006130":"Office","100000015":"U.S. Department of Energy","100013165":"National"},"replaced-by":[],"work-count":44026,"name":"U.S. Department of Energy","descendants":["100006166"],"descendant-work-count":68704,"id":"100000015","tokens":["us"],"replaces":[],"uri":"http:\/\/dx.doi.org\/10.13039\/100000015","hierarchy":{"100000015":{"100006130":{"more":true},"100013165":{},"100006138":{"more":true}}},"alt-names":["DOE"],"location":"United States"}}"#;
554
555        let funder: Response = from_str(funder_str).unwrap();
556
557        assert!(funder.is_funder());
558    }
559
560    #[test]
561    fn prefix_msg_deserialize() {
562        let prefix_str = r#"{"status":"ok","message-type":"prefix","message-version":"1.0.0","message":{"member":"http:\/\/id.crossref.org\/member\/78","name":"Elsevier BV","prefix":"http:\/\/id.crossref.org\/prefix\/10.1016"}}"#;
563
564        let prefix: Response = from_str(prefix_str).unwrap();
565
566        assert!(prefix.is_prefix());
567    }
568
569    #[test]
570    fn members_list_msg_deserialize() {
571        let members_list_str = r#"{"status":"ok","message-type":"member-list","message-version":"1.0.0","message":{"items-per-page":2,"query":{"start-index":0,"search-terms":null},"total-results":10257,"items":[{"last-status-check-time":1551766727771,"primary-name":"Society for Leukocyte Biology","counts":{"total-dois":0,"current-dois":0,"backfile-dois":0},"breakdowns":{"dois-by-issued-year":[]},"prefixes":["10.1189"],"coverage":{"affiliations-current":0,"similarity-checking-current":0,"funders-backfile":0,"licenses-backfile":0,"funders-current":0,"affiliations-backfile":0,"resource-links-backfile":0,"orcids-backfile":0,"update-policies-current":0,"open-references-backfile":0,"orcids-current":0,"similarity-checking-backfile":0,"references-backfile":0,"award-numbers-backfile":0,"update-policies-backfile":0,"licenses-current":0,"award-numbers-current":0,"abstracts-backfile":0,"resource-links-current":0,"abstracts-current":0,"open-references-current":0,"references-current":0},"prefix":[{"value":"10.1189","name":"Society for Leukocyte Biology","public-references":false,"reference-visibility":"limited"}],"id":183,"tokens":["society","for","leukocyte","biology"],"counts-type":{"all":{},"current":{},"backfile":{}},"coverage-type":{"all":null,"backfile":null,"current":null},"flags":{"deposits-abstracts-current":false,"deposits-orcids-current":false,"deposits":false,"deposits-affiliations-backfile":false,"deposits-update-policies-backfile":false,"deposits-similarity-checking-backfile":false,"deposits-award-numbers-current":false,"deposits-resource-links-current":false,"deposits-articles":false,"deposits-affiliations-current":false,"deposits-funders-current":false,"deposits-references-backfile":false,"deposits-abstracts-backfile":false,"deposits-licenses-backfile":false,"deposits-award-numbers-backfile":false,"deposits-open-references-backfile":false,"deposits-open-references-current":false,"deposits-references-current":false,"deposits-resource-links-backfile":false,"deposits-orcids-backfile":false,"deposits-funders-backfile":false,"deposits-update-policies-current":false,"deposits-similarity-checking-current":false,"deposits-licenses-current":false},"location":"9650 Rockville Pike Attn: Lynn Willis Bethesda MD 20814 United States","names":["Society for Leukocyte Biology"]}]}}"#;
572
573        let members_list: Response = from_str(members_list_str).unwrap();
574
575        assert!(members_list.is_member_list());
576    }
577
578    #[test]
579    fn member_msg_deserialize() {
580        let member_str = r#"{"status":"ok","message-type":"member","message-version":"1.0.0","message":{"last-status-check-time":1551766727771,"primary-name":"Society for Leukocyte Biology","counts":{"total-dois":0,"current-dois":0,"backfile-dois":0},"breakdowns":{"dois-by-issued-year":[]},"prefixes":["10.1189"],"coverage":{"affiliations-current":0,"similarity-checking-current":0,"funders-backfile":0,"licenses-backfile":0,"funders-current":0,"affiliations-backfile":0,"resource-links-backfile":0,"orcids-backfile":0,"update-policies-current":0,"open-references-backfile":0,"orcids-current":0,"similarity-checking-backfile":0,"references-backfile":0,"award-numbers-backfile":0,"update-policies-backfile":0,"licenses-current":0,"award-numbers-current":0,"abstracts-backfile":0,"resource-links-current":0,"abstracts-current":0,"open-references-current":0,"references-current":0},"prefix":[{"value":"10.1189","name":"Society for Leukocyte Biology","public-references":false,"reference-visibility":"limited"}],"id":183,"tokens":["society","for","leukocyte","biology"],"counts-type":{"all":{},"current":{},"backfile":{}},"coverage-type":{"all":null,"backfile":null,"current":null},"flags":{"deposits-abstracts-current":false,"deposits-orcids-current":false,"deposits":false,"deposits-affiliations-backfile":false,"deposits-update-policies-backfile":false,"deposits-similarity-checking-backfile":false,"deposits-award-numbers-current":false,"deposits-resource-links-current":false,"deposits-articles":false,"deposits-affiliations-current":false,"deposits-funders-current":false,"deposits-references-backfile":false,"deposits-abstracts-backfile":false,"deposits-licenses-backfile":false,"deposits-award-numbers-backfile":false,"deposits-open-references-backfile":false,"deposits-open-references-current":false,"deposits-references-current":false,"deposits-resource-links-backfile":false,"deposits-orcids-backfile":false,"deposits-funders-backfile":false,"deposits-update-policies-current":false,"deposits-similarity-checking-current":false,"deposits-licenses-current":false},"location":"9650 Rockville Pike Attn: Lynn Willis Bethesda MD 20814 United States","names":["Society for Leukocyte Biology"]}}"#;
581
582        let member: Response = from_str(member_str).unwrap();
583
584        assert!(member.is_member());
585    }
586
587    #[test]
588    fn journals_list_msg_deserialize() {
589        let journal_list_str = r#"{"status":"ok","message-type":"journal-list","message-version":"1.0.0","message":{"items-per-page":2,"query":{"start-index":0,"search-terms":null},"total-results":10257,"items":[{"last-status-check-time":null,"counts":null,"breakdowns":null,"publisher":"Fundacao Educacional de Criciuma- FUCRI","coverage":null,"title":"A INFLU\u00caNCIA DA PUBLICIDADE NA TRANSI\u00c7\u00c3O NUTRICIONAL UMA S\u00cdNTESE PARA ENTENDER A OBESIDADE","subjects":[],"coverage-type":null,"flags":null,"ISSN":[],"issn-type":[]}]}}"#;
590
591        let journal_list: Response = from_str(journal_list_str).unwrap();
592
593        assert!(journal_list.is_journal_list());
594    }
595
596    #[test]
597    fn journal_msg_deserialize() {
598        let journal_str = r#"{"status":"ok","message-type":"journal","message-version":"1.0.0","message":{"last-status-check-time":null,"counts":null,"breakdowns":null,"publisher":"Fundacao Educacional de Criciuma- FUCRI","coverage":null,"title":"A INFLU\u00caNCIA DA PUBLICIDADE NA TRANSI\u00c7\u00c3O NUTRICIONAL UMA S\u00cdNTESE PARA ENTENDER A OBESIDADE","subjects":[],"coverage-type":null,"flags":null,"ISSN":[],"issn-type":[]}}"#;
599
600        let journal: Response = from_str(journal_str).unwrap();
601
602        assert!(journal.is_journal());
603    }
604
605    #[test]
606    fn type_list_msg_deserialize() {
607        let type_list_str = r#"{"status":"ok","message-type":"type-list","message-version":"1.0.0","message":{"total-results":27,"items":[{"id":"book-section","label":"Book Section"},{"id":"monograph","label":"Monograph"}]}}"#;
608        let type_list: Response = from_str(type_list_str).unwrap();
609
610        assert!(type_list.is_type_list());
611    }
612
613    #[test]
614    fn type_msg_deserialize() {
615        let type_str = r#"{"status":"ok","message-type":"type","message-version":"1.0.0","message":{"id":"book-section","label":"Book Section"}}"#;
616        let type_: Response = from_str(type_str).unwrap();
617
618        assert!(type_.is_type());
619    }
620
621    #[test]
622    fn validation_failure_deserialize() {
623        let failure_str = r#"{"status":"failed","message-type":"validation-failure","message":[{"type":"parameter-not-allowed","value":"query.*","message":"This route does not support field query parameters"}]}"#;
624        let failure: Response = from_str(failure_str).unwrap();
625
626        assert!(failure.is_validation_failure());
627    }
628
629    #[test]
630    fn work_msg_deserialize() {
631        let failure_str = r#"{"status":"ok","message-type":"work","message-version":"1.0.0","message":{"indexed":{"date-parts":[[2019,2,14]],"date-time":"2019-02-14T05:10:15Z","timestamp":1550121015066},"reference-count":105,"publisher":"American Psychological Association (APA)","issue":"1","content-domain":{"domain":[],"crossmark-restriction":false},"short-container-title":["American Psychologist"],"DOI":"10.1037\/0003-066x.59.1.29","type":"journal-article","created":{"date-parts":[[2004,1,21]],"date-time":"2004-01-21T14:31:19Z","timestamp":1074695479000},"page":"29-40","source":"Crossref","is-referenced-by-count":83,"title":["How the Mind Hurts and Heals the Body."],"prefix":"10.1037","volume":"59","author":[{"given":"Oakley","family":"Ray","sequence":"first","affiliation":[]}],"member":"15","published-online":{"date-parts":[[2004]]},"container-title":["American Psychologist"],"original-title":[],"language":"en","link":[{"URL":"http:\/\/psycnet.apa.org\/journals\/amp\/59\/1\/29.pdf","content-type":"unspecified","content-version":"vor","intended-application":"similarity-checking"}],"deposited":{"date-parts":[[2018,4,8]],"date-time":"2018-04-08T18:56:17Z","timestamp":1523213777000},"score":1.0,"subtitle":[],"short-title":[],"issued":{"date-parts":[[2004]]},"references-count":105,"journal-issue":{"published-online":{"date-parts":[[2004]]},"issue":"1"},"alternative-id":["2004-10043-004","14736318"],"URL":"http:\/\/dx.doi.org\/10.1037\/0003-066x.59.1.29","relation":{},"ISSN":["1935-990X","0003-066X"],"issn-type":[{"value":"0003-066X","type":"print"},{"value":"1935-990X","type":"electronic"}]}}"#;
632        let work: Response = from_str(failure_str).unwrap();
633
634        assert!(work.is_work());
635    }
636}