Skip to main content

crossref_client/query/
types.rs

1use crate::error::{Error, Result};
2use crate::query::works::{WorksCombiner, WorksIdentQuery};
3use crate::query::{Component, CrossrefQuery, CrossrefRoute, ResourceComponent};
4use serde::{Deserialize, Serialize};
5use std::str::FromStr;
6
7/// Defines [`Type`] together with everything that has to stay in step with it:
8/// the identifier crossref knows each variant by, the label it displays, the
9/// [`FromStr`] that reads one back, and [`Type::ALL`].
10///
11/// The vocabulary is crossref's own and changes -- `grant`, `database` and
12/// `report-component` were added after this crate first modelled it, and
13/// `standard-series` was dropped -- which is what
14/// `the_type_vocabulary_matches_the_api` pins this list against.
15macro_rules! define_types {
16    ($($variant:ident => $id:literal / $label:literal,)*) => {
17        /// One of the work types crossref registers, as listed by `/types`.
18        ///
19        /// ```
20        /// # use crossref_client::Type;
21        /// # use std::str::FromStr;
22        /// assert_eq!(Type::JournalArticle, Type::from_str("journal-article").unwrap());
23        /// assert_eq!("Journal Article", Type::JournalArticle.label());
24        /// ```
25        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
26        #[serde(tag = "id")]
27        pub enum Type {
28            $(
29                #[doc = concat!("`", $id, "`, which crossref labels ", $label)]
30                #[serde(rename = $id)]
31                $variant,
32            )*
33        }
34
35        impl Type {
36            /// Every type crossref registers, in the order `/types` lists them.
37            pub const ALL: &'static [Type] = &[$(Type::$variant,)*];
38
39            /// the display-friendly label crossref gives this type
40            pub fn label(&self) -> &'static str {
41                match self { $(Type::$variant => $label,)* }
42            }
43
44            /// the identifier crossref knows this type by
45            pub fn id(&self) -> &'static str {
46                match self { $(Type::$variant => $id,)* }
47            }
48        }
49
50        impl FromStr for Type {
51            type Err = Error;
52
53            fn from_str(s: &str) -> Result<Self> {
54                match s {
55                    $($id => Ok(Type::$variant),)*
56                    name => Err(Error::InvalidTypeName { name: name.to_string() }),
57                }
58            }
59        }
60    };
61}
62
63define_types! {
64    BookSection => "book-section" / "Book Section",
65    Monograph => "monograph" / "Monograph",
66    ReportComponent => "report-component" / "Report Component",
67    Report => "report" / "Report",
68    PeerReview => "peer-review" / "Peer Review",
69    BookTrack => "book-track" / "Book Track",
70    JournalArticle => "journal-article" / "Journal Article",
71    BookPart => "book-part" / "Part",
72    Other => "other" / "Other",
73    Book => "book" / "Book",
74    JournalVolume => "journal-volume" / "Journal Volume",
75    BookSet => "book-set" / "Book Set",
76    ReferenceEntry => "reference-entry" / "Reference Entry",
77    ProceedingsArticle => "proceedings-article" / "Proceedings Article",
78    Journal => "journal" / "Journal",
79    Component => "component" / "Component",
80    BookChapter => "book-chapter" / "Book Chapter",
81    ProceedingsSeries => "proceedings-series" / "Proceedings Series",
82    ReportSeries => "report-series" / "Report Series",
83    Proceedings => "proceedings" / "Proceedings",
84    Database => "database" / "Database",
85    Standard => "standard" / "Standard",
86    ReferenceBook => "reference-book" / "Reference Book",
87    PostedContent => "posted-content" / "Posted Content",
88    JournalIssue => "journal-issue" / "Journal Issue",
89    Dissertation => "dissertation" / "Dissertation",
90    Grant => "grant" / "Grant",
91    Dataset => "dataset" / "Dataset",
92    BookSeries => "book-series" / "Book Series",
93    EditedBook => "edited-book" / "Edited Book",
94}
95
96/// constructs the request payload for the `/types` route
97///
98/// The route takes `query`, `rows` and `offset`, but answers all three with the
99/// same complete list -- there are only [30 types](Type::ALL), so crossref
100/// serves them in one page and ignores the paging. This crate therefore models
101/// the list, one type, and the works of one type, and nothing else.
102#[derive(Debug, Clone)]
103pub enum Types {
104    /// every available type
105    All,
106    /// target a specific type at `/types/{id}`
107    Identifier(String),
108    /// target a `Work` for a specific type at `/types/{id}/works?query..`
109    Works(WorksIdentQuery),
110}
111
112impl CrossrefRoute for Types {
113    fn route(&self) -> Result<String> {
114        match self {
115            Types::All => Component::Types.route(),
116            Types::Identifier(s) => Ok(format!("{}/{}", Component::Types.route()?, s)),
117            Types::Works(combined) => Self::combined_route(combined),
118        }
119    }
120}
121
122impl CrossrefQuery for Types {
123    fn resource_component(self) -> ResourceComponent {
124        ResourceComponent::Types(self)
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn a_type_deserializes_from_the_record_the_api_sends() {
134        let section = r#"{
135    "id": "book-section",
136    "label": "Book Section"
137  }"#;
138        let ref_type: Type = serde_json::from_str(section).unwrap();
139
140        assert_eq!(Type::BookSection, ref_type);
141    }
142
143    #[test]
144    fn every_type_round_trips_through_from_str() {
145        for type_ in Type::ALL {
146            assert_eq!(*type_, Type::from_str(type_.id()).expect("a known type"));
147        }
148    }
149
150    #[test]
151    fn a_type_crossref_no_longer_registers_is_not_a_type() {
152        // `/types/standard-series` is a `404` -- crossref dropped it
153        assert!(Type::from_str("standard-series").is_err());
154    }
155}