Skip to main content

crossref_client/response/
mod.rs

1mod journal;
2use crate::error::Error;
3use crate::query::Visibility;
4use crate::response::work::*;
5pub use journal::*;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::HashMap;
9use std::fmt;
10
11//pub use crate::response::journal::Journal;
12/// provides the types for a work response
13pub mod work;
14
15pub use crate::response::work::{Work, WorkList};
16
17/// Represents the whole crossref response for a any request.
18///
19/// Which payload the `message` carries is decided by the `message-type` beside
20/// it, which is exactly serde's adjacently tagged enum -- so [`Message`] does
21/// the dispatch and this type is a plain derive.
22#[derive(Debug, Clone, Deserialize, Serialize)]
23#[serde(rename_all = "kebab-case")]
24pub struct Response {
25    /// the status of the request
26    pub status: String,
27    /// the version of the service created this message
28    #[serde(default = "default_msg_version")]
29    pub message_version: String,
30    /// the actual message of the response, and the type naming it
31    #[serde(flatten)]
32    pub message: Message,
33}
34
35/// at some routes the `msg_version` is missing, this returns the default version for a crossref response
36fn default_msg_version() -> String {
37    "1.0.0".to_string()
38}
39
40/// this macro helps to generate a function that checks whether the message is of a specific type
41macro_rules! impl_msg_helper {
42    ($($name:ident -> $ident:ident,)*) => {
43    $(
44        /// checks if the message holds the variant
45        pub fn $name(&self) -> bool {
46            matches!(&self.message, Message::$ident(_))
47        }
48    )+
49    };
50}
51
52impl Response {
53    impl_msg_helper!(
54        is_work_agency -> WorkAgency,
55        is_funder -> Funder,
56        is_prefix -> Prefix,
57        is_work -> Work,
58        is_type -> Type,
59        is_journal -> Journal,
60        is_member -> Member,
61        is_validation_failure -> ValidationFailure,
62        is_type_list -> TypeList,
63        is_work_list -> WorkList,
64        is_member_list -> MemberList,
65        is_journal_list -> JournalList,
66        is_funder_list -> FunderList,
67        is_license_list -> LicenseList,
68        is_style_list -> StyleList,
69    );
70
71    /// checks whether the `message` holds a variant of `RouteNotFound`
72    pub fn is_route_not_found(&self) -> bool {
73        matches!(&self.message, Message::RouteNotFound(_))
74    }
75}
76
77macro_rules! impl_list_response {
78    ($($(#[$meta:meta])* $name:ident<$ty:ty> { $($extra:tt)* })*) => {
79    $(
80        $(#[$meta])*
81        #[derive(Debug, Clone, Deserialize, Serialize)]
82        #[serde(rename_all = "kebab-case")]
83        pub struct $name {
84            /// the number of items that match the response
85            pub total_results: usize,
86            /// crossref responses for large number of items are divided in pages, number of elements to expect in `items`
87            pub items_per_page: Option<usize>,
88            /// if a query was set in the request, this will also be part in the response
89            pub query: Option<QueryResponse>,
90            /// all actual message items of the response
91            pub items: Vec<$ty>,
92            $($extra)*
93        }
94    )+
95    };
96}
97
98impl_list_response!(
99    /// the payload of a `/types` response
100    TypeList<CrossrefType> {
101        /// if facets were part of the request they are also included in the response
102        #[serde(default)]
103        pub facets: FacetMap,
104    }
105    /// the payload of a `/members` response
106    MemberList<Member> {
107        /// if facets were part of the request they are also included in the response
108        #[serde(default)]
109        pub facets: FacetMap,
110    }
111    /// the payload of a `/funders` response
112    FunderList<Funder> {
113        /// if facets were part of the request they are also included in the response
114        #[serde(default)]
115        pub facets: FacetMap,
116    }
117    /// the payload of a `/journals` response
118    ///
119    /// Carries no facets: `/journals` rejects the `facet` parameter, so the
120    /// field this type used to have was always an empty map synthesized by the
121    /// deserializer.
122    JournalList<Journal> {}
123    /// the payload of a `/licenses` response
124    ///
125    /// Carries neither facets nor a query echo -- `/licenses` sends neither.
126    LicenseList<LicenseCount> {}
127    /// the payload of a `/styles` response: the names of the
128    /// [CSL styles](https://citationstyles.org) crossref can render a citation in
129    StyleList<String> {}
130);
131
132/// the different payloads of a response, and the `message-type` that names them
133#[derive(Debug, Clone, Deserialize, Serialize)]
134#[serde(tag = "message-type", content = "message", rename_all = "kebab-case")]
135pub enum Message {
136    /// if a request failed on the server side
137    ValidationFailure(Failures),
138    /// a route could not be found on the server side
139    RouteNotFound(String),
140    /// the agency for a specific work
141    WorkAgency(WorkAgency),
142    /// metadata data for the DOI owner prefix
143    Prefix(Prefix),
144    /// a valid work type
145    Type(CrossrefType),
146    /// a list of valid work types
147    TypeList(TypeList),
148    /// a publication(journal, articles...)
149    Work(Box<Work>),
150    /// a list of publications
151    WorkList(WorkList),
152    /// a crossref member (mostly publishers)
153    Member(Box<Member>),
154    /// a list of crossref members
155    MemberList(MemberList),
156    /// a Journal publication
157    Journal(Box<Journal>),
158    /// list of journal publications
159    JournalList(JournalList),
160    /// a funder in the [funder registry](https://github.com/Crossref/open-funder-registry)
161    Funder(Box<Funder>),
162    /// a list of funder
163    FunderList(FunderList),
164    /// a list of licenses works in the crossref metadata are published under
165    LicenseList(LicenseList),
166    /// a list of the citation styles crossref can render a work in
167    StyleList(StyleList),
168}
169
170impl Message {
171    /// the `message-type` crossref labelled this payload with
172    pub fn message_type(&self) -> MessageType {
173        match self {
174            Message::ValidationFailure(_) => MessageType::ValidationFailure,
175            Message::RouteNotFound(_) => MessageType::RouteNotFound,
176            Message::WorkAgency(_) => MessageType::WorkAgency,
177            Message::Prefix(_) => MessageType::Prefix,
178            Message::Type(_) => MessageType::Type,
179            Message::TypeList(_) => MessageType::TypeList,
180            Message::Work(_) => MessageType::Work,
181            Message::WorkList(_) => MessageType::WorkList,
182            Message::Member(_) => MessageType::Member,
183            Message::MemberList(_) => MessageType::MemberList,
184            Message::Journal(_) => MessageType::Journal,
185            Message::JournalList(_) => MessageType::JournalList,
186            Message::Funder(_) => MessageType::Funder,
187            Message::FunderList(_) => MessageType::FunderList,
188            Message::LicenseList(_) => MessageType::LicenseList,
189            Message::StyleList(_) => MessageType::StyleList,
190        }
191    }
192}
193
194/// how many works in the crossref metadata are published under one license
195#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
196#[serde(rename_all = "kebab-case")]
197pub struct LicenseCount {
198    /// link to the web page describing the license
199    #[serde(rename = "URL")]
200    pub url: String,
201    /// how many works crossref holds that are published under it
202    pub work_count: usize,
203}
204
205#[derive(Debug, Clone, Deserialize, Serialize)]
206/// one of the work types crossref registers, as returned by `/types`
207pub struct CrossrefType {
208    /// the identifier, e.g. `journal-article`
209    pub id: String,
210    /// a display-friendly form of `id`, e.g. `Journal Article`
211    pub label: String,
212}
213
214impl From<crate::query::types::Type> for CrossrefType {
215    fn from(val: crate::query::types::Type) -> Self {
216        CrossrefType {
217            id: val.id().to_string(),
218            label: val.label().to_string(),
219        }
220    }
221}
222
223/// response item for the `/works/{id}/agency` route
224#[derive(Debug, Clone, Deserialize, Serialize)]
225pub struct WorkAgency {
226    /// the DOI fo the work that belongs to the `agency`
227    #[serde(rename = "DOI")]
228    doi: String,
229    /// the agency that owns the work with `doi`
230    agency: Agency,
231}
232
233/// response item for the `/prefix/{id}/` route
234#[derive(Debug, Clone, Deserialize, Serialize)]
235/// response item for the `/prefixes/{id}` route
236pub struct Prefix {
237    /// url of the member that owns the prefix
238    pub member: String,
239    /// the owning member's name
240    pub name: String,
241    /// url of the prefix itself
242    pub prefix: String,
243}
244
245/// all possible `message-type` of a response
246#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
247#[serde(rename_all = "kebab-case")]
248// one variant per `message-type` crossref sends; `as_str` spells each out
249#[allow(missing_docs)]
250pub enum MessageType {
251    WorkAgency,
252    Funder,
253    Prefix,
254    Member,
255    Work,
256    WorkList,
257    FunderList,
258    Type,
259    TypeList,
260    MemberList,
261    Journal,
262    JournalList,
263    LicenseList,
264    StyleList,
265    ValidationFailure,
266    RouteNotFound,
267}
268
269impl MessageType {
270    /// the type identifier for a message
271    pub fn as_str(&self) -> &str {
272        match self {
273            MessageType::WorkAgency => "work-agency",
274            MessageType::Funder => "funder",
275            MessageType::Prefix => "prefix",
276            MessageType::Member => "member",
277            MessageType::MemberList => "member-list",
278            MessageType::Work => "work",
279            MessageType::WorkList => "work-list",
280            MessageType::FunderList => "funder-list",
281            MessageType::Type => "type",
282            MessageType::TypeList => "type-list",
283            MessageType::Journal => "journal",
284            MessageType::JournalList => "journal-list",
285            MessageType::LicenseList => "license-list",
286            MessageType::StyleList => "style-list",
287            MessageType::ValidationFailure => "validation-failure",
288            MessageType::RouteNotFound => "route-not-found",
289        }
290    }
291}
292
293impl std::str::FromStr for MessageType {
294    type Err = Error;
295
296    /// creates a `MessageType` from its crossref identifier
297    fn from_str(s: &str) -> Result<MessageType, Error> {
298        match s {
299            "work-agency" => Ok(MessageType::WorkAgency),
300            "funder" => Ok(MessageType::Funder),
301            "prefix" => Ok(MessageType::Prefix),
302            "member" => Ok(MessageType::Member),
303            "member-list" => Ok(MessageType::MemberList),
304            "work" => Ok(MessageType::Work),
305            "work-list" => Ok(MessageType::WorkList),
306            "funder-list" => Ok(MessageType::FunderList),
307            "type" => Ok(MessageType::Type),
308            "type-list" => Ok(MessageType::TypeList),
309            "journal" => Ok(MessageType::Journal),
310            "journal-list" => Ok(MessageType::JournalList),
311            "license-list" => Ok(MessageType::LicenseList),
312            "style-list" => Ok(MessageType::StyleList),
313            "validation-failure" => Ok(MessageType::ValidationFailure),
314            "route-not-found" => Ok(MessageType::RouteNotFound),
315            _ => Err(Error::InvalidTypeName {
316                name: s.to_string(),
317            }),
318        }
319    }
320}
321
322impl fmt::Display for MessageType {
323    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324        self.as_str().fmt(f)
325    }
326}
327
328/// if a query was set in the request then it is also part of the result
329#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
330#[serde(rename_all = "kebab-case")]
331pub struct QueryResponse {
332    /// from which the returned items start
333    pub start_index: usize,
334    /// the terms that were initially set in the request query
335    pub search_terms: Option<String>,
336}
337
338/// facets are returned as map
339pub type FacetMap = HashMap<String, FacetItem>;
340
341/// if a `facet` was set in a request `FacetMap` will be  in a `List` response as additional field of the message
342#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
343#[serde(rename_all = "kebab-case")]
344pub struct FacetItem {
345    /// represents the length of `values`
346    pub value_count: usize,
347    /// contains the
348    pub values: HashMap<String, usize>,
349}
350
351/// everything crossref objected to in a rejected request
352#[derive(Debug, Clone, Deserialize, Serialize)]
353pub struct Failures(Vec<Failure>);
354
355impl From<Vec<Failure>> for Failures {
356    fn from(failures: Vec<Failure>) -> Self {
357        Failures(failures)
358    }
359}
360
361impl Failures {
362    /// whether crossref listed no objection at all
363    pub fn is_empty(&self) -> bool {
364        self.0.is_empty()
365    }
366
367    /// the individual objections
368    pub fn as_slice(&self) -> &[Failure] {
369        &self.0
370    }
371
372    /// the message of the first objection about a malformed DOI, if any
373    pub fn get_doi_error(&self) -> Option<String> {
374        self.0
375            .iter()
376            .find(|f| f.is_doi())
377            .map(|f| f.message.clone())
378    }
379}
380
381impl fmt::Display for Failures {
382    /// Renders the objections as a `; ` separated list of their messages.
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        for (i, failure) in self.0.iter().enumerate() {
385            if i > 0 {
386                f.write_str("; ")?;
387            }
388            f.write_str(&failure.message)?;
389        }
390        Ok(())
391    }
392}
393
394/// a single thing crossref objected to in a rejected request
395#[derive(Debug, Clone, Deserialize, Serialize)]
396#[serde(rename_all = "kebab-case")]
397pub struct Failure {
398    /// identifier for the kind of objection, e.g. `filter-not-available`
399    #[serde(rename = "type")]
400    pub type_: String,
401    /// the value that caused the failure
402    pub value: String,
403    /// the message from the server
404    pub message: String,
405}
406
407impl Failure {
408    /// whether this objection is about a malformed DOI
409    pub fn is_doi(&self) -> bool {
410        self.type_ == "doi-not-valid"
411    }
412}
413
414/// response item for the `/funder/{id}` route
415#[derive(Debug, Clone, Default, Deserialize, Serialize)]
416#[serde(rename_all = "kebab-case", default)]
417// a mirror of crossref's funder record; the field names are its own
418#[allow(missing_docs)]
419pub struct Funder {
420    pub hierarchy_names: HashMap<String, Option<String>>,
421    pub hierarchy: HashMap<String, HashMap<String, HashMap<String, bool>>>,
422    pub id: String,
423    pub location: String,
424    pub work_count: Option<usize>,
425    pub descendant_work_count: Option<usize>,
426    pub descendants: Vec<String>,
427    pub name: String,
428    pub alt_names: Vec<String>,
429    pub uri: String,
430    pub replaces: Vec<String>,
431    pub replaced_by: Vec<String>,
432    pub tokens: Vec<String>,
433}
434
435/// response item for the `/member/{id}` route
436#[derive(Debug, Clone, Default, Deserialize, Serialize)]
437#[serde(rename_all = "kebab-case", default)]
438// a mirror of crossref's member record; the field names are its own
439#[allow(missing_docs)]
440pub struct Member {
441    pub primary_name: String,
442    pub last_status_check_time: usize,
443    pub counts: Counts,
444    pub breakdowns: Breakdowns,
445    pub prefixes: Vec<String>,
446    pub coverage: Coverage,
447    pub prefix: Vec<RefPrefix>,
448    pub id: usize,
449    pub tokens: Vec<String>,
450    pub counts_type: HashMap<String, HashMap<String, usize>>,
451    pub coverage_type: Value,
452    pub flags: HashMap<String, bool>,
453    pub location: String,
454    pub names: Vec<String>,
455}
456
457#[derive(Debug, Clone, Default, Deserialize, Serialize)]
458#[serde(rename_all = "kebab-case", default)]
459/// how many DOIs crossref holds for a member
460pub struct Counts {
461    /// every DOI the member has deposited, current and backfile
462    pub total_dois: usize,
463    /// DOIs for material published within the last two years
464    pub current_dois: usize,
465    /// DOIs for material published more than two years ago
466    pub backfile_dois: usize,
467}
468
469#[derive(Debug, Clone, Default, Deserialize, Serialize)]
470#[serde(rename_all = "kebab-case", default)]
471/// how a member's DOIs are spread across publication years
472pub struct Breakdowns {
473    /// `[year, count]` pairs, in the order crossref returned them
474    pub dois_by_issued_year: Vec<Vec<u32>>,
475}
476
477#[derive(Debug, Clone, Default, Deserialize, Serialize)]
478#[serde(rename_all = "kebab-case", default)]
479// one `f32` per optional field crossref tracks, each the share of the member's
480// deposits that carry it; naming them individually would only restate the field
481#[allow(missing_docs)]
482pub struct Coverage {
483    pub affiliations_current: f32,
484    pub similarity_checking_current: f32,
485    pub funders_backfile: f32,
486    pub licenses_backfile: f32,
487    pub funders_current: f32,
488    pub affiliations_backfile: f32,
489    pub resource_links_backfile: f32,
490    pub orcids_backfile: f32,
491    pub update_policies_current: f32,
492    pub open_references_backfile: f32,
493    pub orcids_current: f32,
494    pub similarity_checking_backfile: f32,
495    pub references_backfile: f32,
496    pub award_numbers_backfile: f32,
497    pub update_policies_backfile: f32,
498    pub licenses_current: f32,
499    pub award_numbers_current: f32,
500    pub abstracts_backfile: f32,
501    pub resource_links_current: f32,
502    pub abstracts_current: f32,
503    pub open_references_current: f32,
504    pub references_current: f32,
505}
506
507#[derive(Debug, Clone, Default, Deserialize, Serialize)]
508#[serde(rename_all = "kebab-case", default)]
509/// a DOI prefix a member owns, and what it exposes through it
510pub struct RefPrefix {
511    /// the prefix itself, e.g. `10.1016`
512    pub value: String,
513    /// the name the member deposits under this prefix
514    pub name: String,
515    /// whether the member has opened its references for this prefix
516    pub public_references: bool,
517    /// who may read the references deposited under this prefix
518    pub reference_visibility: Option<Visibility>,
519}
520
521// response item for the `/journal/{id}` route
522//#[derive(Debug, Clone, Deserialize, Serialize)]
523//#[serde(rename_all = "kebab-case")]
524//#[allow(missing_docs)]
525//pub struct Journal {
526//    /// could not determine type, possible PartialDateParts
527//    pub last_status_check_time: Option<Value>,
528//    pub counts: Option<Value>,
529//    pub breakdowns: Option<Value>,
530//    pub publisher: Option<String>,
531//    pub coverage: Option<Value>,
532//    pub title: Option<String>,
533//    pub subjects: Vec<Value>,
534//    pub coverage_type: Option<Value>,
535//    pub flags: Option<Value>,
536//    #[serde(rename = "ISSN")]
537//    pub issn: Vec<String>,
538//    pub issn_type: Vec<String>,
539//}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use serde_json::*;
545
546    #[test]
547    fn facets_deserialize() {
548        let facets = r#"{
549      "affiliation": {
550        "value-count": 5,
551        "values": {
552          "of": 177247,
553          "university": 147649,
554          "department": 128741,
555          "and": 102652,
556          "medicine": 96232
557        }
558      },
559      "orcid": {
560        "value-count": 10,
561        "values": {
562          "http:\/\/orcid.org\/0000-0002-0270-1711": 67
563        }
564      }
565    }"#;
566
567        let _: FacetMap = from_str(facets).unwrap();
568    }
569
570    #[test]
571    fn agency_msg_deserialize() {
572        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"}}}"#;
573
574        let agency: Response = from_str(agency_str).unwrap();
575
576        assert!(agency.is_work_agency());
577    }
578
579    #[test]
580    fn funder_list_msg_deserialize() {
581        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",
582  "location": "Norway",
583  "name": "Norsk  Sykepleierforbund",
584  "alt-names": [
585    "NSF"
586  ],
587  "uri": "http:\/\/dx.doi.org\/10.13039\/501100004190",
588  "replaces": [],
589  "replaced-by": [],
590  "tokens": [
591    "norsk"
592  ]
593}]}}"#;
594
595        let funders: Response = from_str(funders_str).unwrap();
596
597        assert!(funders.is_funder_list());
598    }
599
600    #[test]
601    fn funder_msg_deserialize() {
602        let funder_str = r#"{"status":"ok","message-type":"funder","message-version":"1.0.0","message":{ "id": "501100004190",
603  "location": "Norway",
604  "name": "Norsk  Sykepleierforbund",
605  "alt-names": [
606    "NSF"
607  ],
608  "uri": "http:\/\/dx.doi.org\/10.13039\/501100004190",
609  "replaces": [],
610  "replaced-by": [],
611  "tokens": [
612    "norsk"
613  ],
614  "work-count": 43,
615  "descendants": [],
616  "hierarchy-names": {
617    "100000019": "National Hemophilia Foundation"
618  },
619  "descendant-work-count": 43,
620    "hierarchy": {
621      "100000019": {}
622  }
623}}"#;
624
625        let funder: Response = from_str(funder_str).unwrap();
626
627        assert!(funder.is_funder());
628    }
629
630    #[test]
631    fn funder_msg_deserialize2() {
632        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"}}"#;
633
634        let funder: Response = from_str(funder_str).unwrap();
635
636        assert!(funder.is_funder());
637    }
638
639    #[test]
640    fn prefix_msg_deserialize() {
641        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"}}"#;
642
643        let prefix: Response = from_str(prefix_str).unwrap();
644
645        assert!(prefix.is_prefix());
646    }
647
648    #[test]
649    fn members_list_msg_deserialize() {
650        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"]}]}}"#;
651
652        let members_list: Response = from_str(members_list_str).unwrap();
653
654        assert!(members_list.is_member_list());
655    }
656
657    #[test]
658    fn member_msg_deserialize() {
659        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"]}}"#;
660
661        let member: Response = from_str(member_str).unwrap();
662
663        assert!(member.is_member());
664    }
665
666    #[test]
667    fn journals_list_msg_deserialize() {
668        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":[]}]}}"#;
669
670        let journal_list: Response = from_str(journal_list_str).unwrap();
671
672        assert!(journal_list.is_journal_list());
673    }
674
675    #[test]
676    fn journal_msg_deserialize() {
677        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":[]}}"#;
678
679        let journal: Response = from_str(journal_str).unwrap();
680
681        assert!(journal.is_journal());
682    }
683
684    #[test]
685    fn type_list_msg_deserialize() {
686        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"}]}}"#;
687        let type_list: Response = from_str(type_list_str).unwrap();
688
689        assert!(type_list.is_type_list());
690    }
691
692    #[test]
693    fn type_msg_deserialize() {
694        let type_str = r#"{"status":"ok","message-type":"type","message-version":"1.0.0","message":{"id":"book-section","label":"Book Section"}}"#;
695        let type_: Response = from_str(type_str).unwrap();
696
697        assert!(type_.is_type());
698    }
699
700    #[test]
701    fn validation_failure_deserialize() {
702        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"}]}"#;
703        let failure: Response = from_str(failure_str).unwrap();
704
705        assert!(failure.is_validation_failure());
706    }
707
708    #[test]
709    fn work_msg_deserialize() {
710        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"}]}}"#;
711        let work: Response = from_str(failure_str).unwrap();
712
713        assert!(work.is_work());
714    }
715}