crossref-client 0.2.0

An async Rust client for the Crossref REST API
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
mod journal;
use crate::error::Error;
use crate::query::Visibility;
use crate::response::work::*;
pub use journal::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;

//pub use crate::response::journal::Journal;
/// provides the types for a work response
pub mod work;

pub use crate::response::work::{Work, WorkList};

/// Represents the whole crossref response for a any request.
///
/// Which payload the `message` carries is decided by the `message-type` beside
/// it, which is exactly serde's adjacently tagged enum -- so [`Message`] does
/// the dispatch and this type is a plain derive.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Response {
    /// the status of the request
    pub status: String,
    /// the version of the service created this message
    #[serde(default = "default_msg_version")]
    pub message_version: String,
    /// the actual message of the response, and the type naming it
    #[serde(flatten)]
    pub message: Message,
}

/// at some routes the `msg_version` is missing, this returns the default version for a crossref response
fn default_msg_version() -> String {
    "1.0.0".to_string()
}

/// this macro helps to generate a function that checks whether the message is of a specific type
macro_rules! impl_msg_helper {
    ($($name:ident -> $ident:ident,)*) => {
    $(
        /// checks if the message holds the variant
        pub fn $name(&self) -> bool {
            matches!(&self.message, Message::$ident(_))
        }
    )+
    };
}

impl Response {
    impl_msg_helper!(
        is_work_agency -> WorkAgency,
        is_funder -> Funder,
        is_prefix -> Prefix,
        is_work -> Work,
        is_type -> Type,
        is_journal -> Journal,
        is_member -> Member,
        is_validation_failure -> ValidationFailure,
        is_type_list -> TypeList,
        is_work_list -> WorkList,
        is_member_list -> MemberList,
        is_journal_list -> JournalList,
        is_funder_list -> FunderList,
        is_license_list -> LicenseList,
        is_style_list -> StyleList,
    );

    /// checks whether the `message` holds a variant of `RouteNotFound`
    pub fn is_route_not_found(&self) -> bool {
        matches!(&self.message, Message::RouteNotFound(_))
    }
}

macro_rules! impl_list_response {
    ($($(#[$meta:meta])* $name:ident<$ty:ty> { $($extra:tt)* })*) => {
    $(
        $(#[$meta])*
        #[derive(Debug, Clone, Deserialize, Serialize)]
        #[serde(rename_all = "kebab-case")]
        pub struct $name {
            /// the number of items that match the response
            pub total_results: usize,
            /// crossref responses for large number of items are divided in pages, number of elements to expect in `items`
            pub items_per_page: Option<usize>,
            /// if a query was set in the request, this will also be part in the response
            pub query: Option<QueryResponse>,
            /// all actual message items of the response
            pub items: Vec<$ty>,
            $($extra)*
        }
    )+
    };
}

impl_list_response!(
    /// the payload of a `/types` response
    TypeList<CrossrefType> {
        /// if facets were part of the request they are also included in the response
        #[serde(default)]
        pub facets: FacetMap,
    }
    /// the payload of a `/members` response
    MemberList<Member> {
        /// if facets were part of the request they are also included in the response
        #[serde(default)]
        pub facets: FacetMap,
    }
    /// the payload of a `/funders` response
    FunderList<Funder> {
        /// if facets were part of the request they are also included in the response
        #[serde(default)]
        pub facets: FacetMap,
    }
    /// the payload of a `/journals` response
    ///
    /// Carries no facets: `/journals` rejects the `facet` parameter, so the
    /// field this type used to have was always an empty map synthesized by the
    /// deserializer.
    JournalList<Journal> {}
    /// the payload of a `/licenses` response
    ///
    /// Carries neither facets nor a query echo -- `/licenses` sends neither.
    LicenseList<LicenseCount> {}
    /// the payload of a `/styles` response: the names of the
    /// [CSL styles](https://citationstyles.org) crossref can render a citation in
    StyleList<String> {}
);

/// the different payloads of a response, and the `message-type` that names them
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "message-type", content = "message", rename_all = "kebab-case")]
pub enum Message {
    /// if a request failed on the server side
    ValidationFailure(Failures),
    /// a route could not be found on the server side
    RouteNotFound(String),
    /// the agency for a specific work
    WorkAgency(WorkAgency),
    /// metadata data for the DOI owner prefix
    Prefix(Prefix),
    /// a valid work type
    Type(CrossrefType),
    /// a list of valid work types
    TypeList(TypeList),
    /// a publication(journal, articles...)
    Work(Box<Work>),
    /// a list of publications
    WorkList(WorkList),
    /// a crossref member (mostly publishers)
    Member(Box<Member>),
    /// a list of crossref members
    MemberList(MemberList),
    /// a Journal publication
    Journal(Box<Journal>),
    /// list of journal publications
    JournalList(JournalList),
    /// a funder in the [funder registry](https://github.com/Crossref/open-funder-registry)
    Funder(Box<Funder>),
    /// a list of funder
    FunderList(FunderList),
    /// a list of licenses works in the crossref metadata are published under
    LicenseList(LicenseList),
    /// a list of the citation styles crossref can render a work in
    StyleList(StyleList),
}

impl Message {
    /// the `message-type` crossref labelled this payload with
    pub fn message_type(&self) -> MessageType {
        match self {
            Message::ValidationFailure(_) => MessageType::ValidationFailure,
            Message::RouteNotFound(_) => MessageType::RouteNotFound,
            Message::WorkAgency(_) => MessageType::WorkAgency,
            Message::Prefix(_) => MessageType::Prefix,
            Message::Type(_) => MessageType::Type,
            Message::TypeList(_) => MessageType::TypeList,
            Message::Work(_) => MessageType::Work,
            Message::WorkList(_) => MessageType::WorkList,
            Message::Member(_) => MessageType::Member,
            Message::MemberList(_) => MessageType::MemberList,
            Message::Journal(_) => MessageType::Journal,
            Message::JournalList(_) => MessageType::JournalList,
            Message::Funder(_) => MessageType::Funder,
            Message::FunderList(_) => MessageType::FunderList,
            Message::LicenseList(_) => MessageType::LicenseList,
            Message::StyleList(_) => MessageType::StyleList,
        }
    }
}

/// how many works in the crossref metadata are published under one license
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct LicenseCount {
    /// link to the web page describing the license
    #[serde(rename = "URL")]
    pub url: String,
    /// how many works crossref holds that are published under it
    pub work_count: usize,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
/// one of the work types crossref registers, as returned by `/types`
pub struct CrossrefType {
    /// the identifier, e.g. `journal-article`
    pub id: String,
    /// a display-friendly form of `id`, e.g. `Journal Article`
    pub label: String,
}

impl From<crate::query::types::Type> for CrossrefType {
    fn from(val: crate::query::types::Type) -> Self {
        CrossrefType {
            id: val.id().to_string(),
            label: val.label().to_string(),
        }
    }
}

/// response item for the `/works/{id}/agency` route
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WorkAgency {
    /// the DOI fo the work that belongs to the `agency`
    #[serde(rename = "DOI")]
    doi: String,
    /// the agency that owns the work with `doi`
    agency: Agency,
}

/// response item for the `/prefix/{id}/` route
#[derive(Debug, Clone, Deserialize, Serialize)]
/// response item for the `/prefixes/{id}` route
pub struct Prefix {
    /// url of the member that owns the prefix
    pub member: String,
    /// the owning member's name
    pub name: String,
    /// url of the prefix itself
    pub prefix: String,
}

/// all possible `message-type` of a response
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
// one variant per `message-type` crossref sends; `as_str` spells each out
#[allow(missing_docs)]
pub enum MessageType {
    WorkAgency,
    Funder,
    Prefix,
    Member,
    Work,
    WorkList,
    FunderList,
    Type,
    TypeList,
    MemberList,
    Journal,
    JournalList,
    LicenseList,
    StyleList,
    ValidationFailure,
    RouteNotFound,
}

impl MessageType {
    /// the type identifier for a message
    pub fn as_str(&self) -> &str {
        match self {
            MessageType::WorkAgency => "work-agency",
            MessageType::Funder => "funder",
            MessageType::Prefix => "prefix",
            MessageType::Member => "member",
            MessageType::MemberList => "member-list",
            MessageType::Work => "work",
            MessageType::WorkList => "work-list",
            MessageType::FunderList => "funder-list",
            MessageType::Type => "type",
            MessageType::TypeList => "type-list",
            MessageType::Journal => "journal",
            MessageType::JournalList => "journal-list",
            MessageType::LicenseList => "license-list",
            MessageType::StyleList => "style-list",
            MessageType::ValidationFailure => "validation-failure",
            MessageType::RouteNotFound => "route-not-found",
        }
    }
}

impl std::str::FromStr for MessageType {
    type Err = Error;

    /// creates a `MessageType` from its crossref identifier
    fn from_str(s: &str) -> Result<MessageType, Error> {
        match s {
            "work-agency" => Ok(MessageType::WorkAgency),
            "funder" => Ok(MessageType::Funder),
            "prefix" => Ok(MessageType::Prefix),
            "member" => Ok(MessageType::Member),
            "member-list" => Ok(MessageType::MemberList),
            "work" => Ok(MessageType::Work),
            "work-list" => Ok(MessageType::WorkList),
            "funder-list" => Ok(MessageType::FunderList),
            "type" => Ok(MessageType::Type),
            "type-list" => Ok(MessageType::TypeList),
            "journal" => Ok(MessageType::Journal),
            "journal-list" => Ok(MessageType::JournalList),
            "license-list" => Ok(MessageType::LicenseList),
            "style-list" => Ok(MessageType::StyleList),
            "validation-failure" => Ok(MessageType::ValidationFailure),
            "route-not-found" => Ok(MessageType::RouteNotFound),
            _ => Err(Error::InvalidTypeName {
                name: s.to_string(),
            }),
        }
    }
}

impl fmt::Display for MessageType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

/// if a query was set in the request then it is also part of the result
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct QueryResponse {
    /// from which the returned items start
    pub start_index: usize,
    /// the terms that were initially set in the request query
    pub search_terms: Option<String>,
}

/// facets are returned as map
pub type FacetMap = HashMap<String, FacetItem>;

/// if a `facet` was set in a request `FacetMap` will be  in a `List` response as additional field of the message
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct FacetItem {
    /// represents the length of `values`
    pub value_count: usize,
    /// contains the
    pub values: HashMap<String, usize>,
}

/// everything crossref objected to in a rejected request
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Failures(Vec<Failure>);

impl From<Vec<Failure>> for Failures {
    fn from(failures: Vec<Failure>) -> Self {
        Failures(failures)
    }
}

impl Failures {
    /// whether crossref listed no objection at all
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// the individual objections
    pub fn as_slice(&self) -> &[Failure] {
        &self.0
    }

    /// the message of the first objection about a malformed DOI, if any
    pub fn get_doi_error(&self) -> Option<String> {
        self.0
            .iter()
            .find(|f| f.is_doi())
            .map(|f| f.message.clone())
    }
}

impl fmt::Display for Failures {
    /// Renders the objections as a `; ` separated list of their messages.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, failure) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_str("; ")?;
            }
            f.write_str(&failure.message)?;
        }
        Ok(())
    }
}

/// a single thing crossref objected to in a rejected request
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Failure {
    /// identifier for the kind of objection, e.g. `filter-not-available`
    #[serde(rename = "type")]
    pub type_: String,
    /// the value that caused the failure
    pub value: String,
    /// the message from the server
    pub message: String,
}

impl Failure {
    /// whether this objection is about a malformed DOI
    pub fn is_doi(&self) -> bool {
        self.type_ == "doi-not-valid"
    }
}

/// response item for the `/funder/{id}` route
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
// a mirror of crossref's funder record; the field names are its own
#[allow(missing_docs)]
pub struct Funder {
    pub hierarchy_names: HashMap<String, Option<String>>,
    pub hierarchy: HashMap<String, HashMap<String, HashMap<String, bool>>>,
    pub id: String,
    pub location: String,
    pub work_count: Option<usize>,
    pub descendant_work_count: Option<usize>,
    pub descendants: Vec<String>,
    pub name: String,
    pub alt_names: Vec<String>,
    pub uri: String,
    pub replaces: Vec<String>,
    pub replaced_by: Vec<String>,
    pub tokens: Vec<String>,
}

/// response item for the `/member/{id}` route
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
// a mirror of crossref's member record; the field names are its own
#[allow(missing_docs)]
pub struct Member {
    pub primary_name: String,
    pub last_status_check_time: usize,
    pub counts: Counts,
    pub breakdowns: Breakdowns,
    pub prefixes: Vec<String>,
    pub coverage: Coverage,
    pub prefix: Vec<RefPrefix>,
    pub id: usize,
    pub tokens: Vec<String>,
    pub counts_type: HashMap<String, HashMap<String, usize>>,
    pub coverage_type: Value,
    pub flags: HashMap<String, bool>,
    pub location: String,
    pub names: Vec<String>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
/// how many DOIs crossref holds for a member
pub struct Counts {
    /// every DOI the member has deposited, current and backfile
    pub total_dois: usize,
    /// DOIs for material published within the last two years
    pub current_dois: usize,
    /// DOIs for material published more than two years ago
    pub backfile_dois: usize,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
/// how a member's DOIs are spread across publication years
pub struct Breakdowns {
    /// `[year, count]` pairs, in the order crossref returned them
    pub dois_by_issued_year: Vec<Vec<u32>>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
// one `f32` per optional field crossref tracks, each the share of the member's
// deposits that carry it; naming them individually would only restate the field
#[allow(missing_docs)]
pub struct Coverage {
    pub affiliations_current: f32,
    pub similarity_checking_current: f32,
    pub funders_backfile: f32,
    pub licenses_backfile: f32,
    pub funders_current: f32,
    pub affiliations_backfile: f32,
    pub resource_links_backfile: f32,
    pub orcids_backfile: f32,
    pub update_policies_current: f32,
    pub open_references_backfile: f32,
    pub orcids_current: f32,
    pub similarity_checking_backfile: f32,
    pub references_backfile: f32,
    pub award_numbers_backfile: f32,
    pub update_policies_backfile: f32,
    pub licenses_current: f32,
    pub award_numbers_current: f32,
    pub abstracts_backfile: f32,
    pub resource_links_current: f32,
    pub abstracts_current: f32,
    pub open_references_current: f32,
    pub references_current: f32,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
/// a DOI prefix a member owns, and what it exposes through it
pub struct RefPrefix {
    /// the prefix itself, e.g. `10.1016`
    pub value: String,
    /// the name the member deposits under this prefix
    pub name: String,
    /// whether the member has opened its references for this prefix
    pub public_references: bool,
    /// who may read the references deposited under this prefix
    pub reference_visibility: Option<Visibility>,
}

// response item for the `/journal/{id}` route
//#[derive(Debug, Clone, Deserialize, Serialize)]
//#[serde(rename_all = "kebab-case")]
//#[allow(missing_docs)]
//pub struct Journal {
//    /// could not determine type, possible PartialDateParts
//    pub last_status_check_time: Option<Value>,
//    pub counts: Option<Value>,
//    pub breakdowns: Option<Value>,
//    pub publisher: Option<String>,
//    pub coverage: Option<Value>,
//    pub title: Option<String>,
//    pub subjects: Vec<Value>,
//    pub coverage_type: Option<Value>,
//    pub flags: Option<Value>,
//    #[serde(rename = "ISSN")]
//    pub issn: Vec<String>,
//    pub issn_type: Vec<String>,
//}

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

    #[test]
    fn facets_deserialize() {
        let facets = r#"{
      "affiliation": {
        "value-count": 5,
        "values": {
          "of": 177247,
          "university": 147649,
          "department": 128741,
          "and": 102652,
          "medicine": 96232
        }
      },
      "orcid": {
        "value-count": 10,
        "values": {
          "http:\/\/orcid.org\/0000-0002-0270-1711": 67
        }
      }
    }"#;

        let _: FacetMap = from_str(facets).unwrap();
    }

    #[test]
    fn agency_msg_deserialize() {
        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"}}}"#;

        let agency: Response = from_str(agency_str).unwrap();

        assert!(agency.is_work_agency());
    }

    #[test]
    fn funder_list_msg_deserialize() {
        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",
  "location": "Norway",
  "name": "Norsk  Sykepleierforbund",
  "alt-names": [
    "NSF"
  ],
  "uri": "http:\/\/dx.doi.org\/10.13039\/501100004190",
  "replaces": [],
  "replaced-by": [],
  "tokens": [
    "norsk"
  ]
}]}}"#;

        let funders: Response = from_str(funders_str).unwrap();

        assert!(funders.is_funder_list());
    }

    #[test]
    fn funder_msg_deserialize() {
        let funder_str = r#"{"status":"ok","message-type":"funder","message-version":"1.0.0","message":{ "id": "501100004190",
  "location": "Norway",
  "name": "Norsk  Sykepleierforbund",
  "alt-names": [
    "NSF"
  ],
  "uri": "http:\/\/dx.doi.org\/10.13039\/501100004190",
  "replaces": [],
  "replaced-by": [],
  "tokens": [
    "norsk"
  ],
  "work-count": 43,
  "descendants": [],
  "hierarchy-names": {
    "100000019": "National Hemophilia Foundation"
  },
  "descendant-work-count": 43,
    "hierarchy": {
      "100000019": {}
  }
}}"#;

        let funder: Response = from_str(funder_str).unwrap();

        assert!(funder.is_funder());
    }

    #[test]
    fn funder_msg_deserialize2() {
        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"}}"#;

        let funder: Response = from_str(funder_str).unwrap();

        assert!(funder.is_funder());
    }

    #[test]
    fn prefix_msg_deserialize() {
        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"}}"#;

        let prefix: Response = from_str(prefix_str).unwrap();

        assert!(prefix.is_prefix());
    }

    #[test]
    fn members_list_msg_deserialize() {
        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"]}]}}"#;

        let members_list: Response = from_str(members_list_str).unwrap();

        assert!(members_list.is_member_list());
    }

    #[test]
    fn member_msg_deserialize() {
        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"]}}"#;

        let member: Response = from_str(member_str).unwrap();

        assert!(member.is_member());
    }

    #[test]
    fn journals_list_msg_deserialize() {
        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":[]}]}}"#;

        let journal_list: Response = from_str(journal_list_str).unwrap();

        assert!(journal_list.is_journal_list());
    }

    #[test]
    fn journal_msg_deserialize() {
        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":[]}}"#;

        let journal: Response = from_str(journal_str).unwrap();

        assert!(journal.is_journal());
    }

    #[test]
    fn type_list_msg_deserialize() {
        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"}]}}"#;
        let type_list: Response = from_str(type_list_str).unwrap();

        assert!(type_list.is_type_list());
    }

    #[test]
    fn type_msg_deserialize() {
        let type_str = r#"{"status":"ok","message-type":"type","message-version":"1.0.0","message":{"id":"book-section","label":"Book Section"}}"#;
        let type_: Response = from_str(type_str).unwrap();

        assert!(type_.is_type());
    }

    #[test]
    fn validation_failure_deserialize() {
        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"}]}"#;
        let failure: Response = from_str(failure_str).unwrap();

        assert!(failure.is_validation_failure());
    }

    #[test]
    fn work_msg_deserialize() {
        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"}]}}"#;
        let work: Response = from_str(failure_str).unwrap();

        assert!(work.is_work());
    }
}