Skip to main content

crossref/response/
work.rs

1// see https://github.com/Crossref/rest-api-doc/blob/master/api_format.md
2
3use crate::response::{FacetMap, QueryResponse};
4use chrono::NaiveDate;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8/// A hashmap containing relation name, `Relation` pairs.
9/// [crossref rest-api-doc](https://github.com/CrossRef/rest-api-doc/blob/master/api_format.md#relations)
10/// However it seems, that the value of the relation name can also be an array.
11/// Therefor the `serde_json::Value` type is used instead to prevent an invalid length error
12pub type Relations = std::collections::HashMap<String, Value>;
13
14#[derive(Debug, Clone, Deserialize, Serialize)]
15#[serde(rename_all = "kebab-case")]
16#[allow(missing_docs)]
17pub struct WorkList {
18    pub facets: FacetMap,
19    /// the number of items that match the response
20    pub total_results: usize,
21    /// crossref responses for large number of items are divided in pages, number of elements to expect in `items`
22    pub items_per_page: Option<usize>,
23    /// if a query was set in the request, this will also be part in the response
24    pub query: Option<QueryResponse>,
25    /// all work items that are returned
26    pub items: Vec<Work>,
27    /// deep page through `/works` result sets
28    pub next_cursor: Option<String>,
29}
30
31/// the main return type of the crossref api
32/// represents a publication
33/// based on the [crossref rest-api-doc](https://github.com/CrossRef/rest-api-doc/blob/master/api_format.md#work)
34/// with minor adjustments
35#[derive(Debug, Clone, Deserialize, Serialize)]
36#[serde(rename_all = "kebab-case")]
37#[allow(missing_docs)]
38pub struct Work {
39    /// Name of work's publisher
40    pub publisher: String,
41    /// Work titles, including translated titles
42    pub title: Vec<String>,
43    /// Work titles in the work's original publication language
44    pub original_title: Option<Vec<String>>,
45    /// the language of this work
46    pub language: Option<String>,
47    /// Abstract as a JSON string or a JATS XML snippet encoded into a JSON string
48    pub short_title: Option<Vec<String>>,
49    /// Abstract as a JSON string or a JATS XML snippet encoded into a JSON string
50    #[serde(rename = "abstract")]
51    pub abstract_: Option<String>,
52    /// Count of outbound references deposited with Crossref
53    pub references_count: i32,
54    /// Count of inbound references deposited with Crossref
55    pub is_referenced_by_count: i32,
56    /// Currently always `Crossref`
57    pub source: String,
58    pub journal_issue: Option<Issue>,
59    /// DOI prefix identifier of the form `http://id.crossref.org/prefix/DOI_PREFIX`
60    pub prefix: String,
61    /// DOI of the work
62    #[serde(rename = "DOI")]
63    pub doi: String,
64    /// URL form of the work's DOI
65    #[serde(rename = "URL")]
66    pub url: String,
67    /// Member identifier of the form `http://id.crossref.org/member/MEMBER_ID`
68    pub member: String,
69    /// Enumeration, one of the type ids from `https://api.crossref.org/v1/types`
70    #[serde(rename = "type")]
71    pub type_: String,
72    /// the day this work entry was created
73    pub created: Option<Date>,
74    /// Date on which the DOI was first registered
75    pub date: Option<Date>,
76    /// Date on which the work metadata was most recently updated
77    pub deposited: Option<Date>,
78    /// the score of the publication if any
79    /// not included in the crossrif api spec
80    pub score: Option<f32>,
81    /// Date on which the work metadata was most recently indexed.
82    /// Re-indexing does not imply a metadata change, see `deposited` for the most recent metadata change date
83    pub indexed: Date,
84    /// Earliest of `published-print` and `published-online`
85    pub issued: PartialDate,
86    /// ate on which posted content was made available online
87    pub posted: Option<PartialDate>,
88    /// Date on which a work was accepted, after being submitted, during a submission process
89    pub accepted: Option<PartialDate>,
90    /// Work subtitles, including original language and translated
91    pub subtitle: Option<Vec<String>>,
92    /// Full titles of the containing work (usually a book or journal)
93    pub container_title: Option<Vec<String>>,
94    /// Abbreviated titles of the containing work
95    pub short_container_title: Option<Vec<String>>,
96    /// Group title for posted content
97    pub group_title: Option<String>,
98    /// Issue number of an article's journal
99    pub issue: Option<String>,
100    /// Volume number of an article's journal
101    pub volume: Option<String>,
102    /// Pages numbers of an article within its journal
103    pub page: Option<String>,
104    /// the number of the corresponding article
105    pub article_number: Option<String>,
106    /// Date on which the work was published in print
107    pub published_print: Option<PartialDate>,
108    /// Date on which the work was published online
109    pub published_online: Option<PartialDate>,
110    /// Subject category names, a controlled vocabulary from Sci-Val.
111    /// Available for most journal articles
112    pub subject: Option<Vec<String>>,
113    #[serde(rename = "ISSN")]
114    pub issn: Option<Vec<String>>,
115    /// List of ISSNs with ISSN type information
116    pub issn_type: Option<Vec<ISSN>>,
117    #[serde(rename = "ISBN")]
118    pub isbn: Option<Vec<String>>,
119    pub archive: Option<Vec<String>>,
120    pub license: Option<Vec<License>>,
121    pub funder: Option<Vec<FundingBody>>,
122    pub assertion: Option<Vec<Assertion>>,
123    pub author: Option<Vec<Contributor>>,
124    pub editor: Option<Vec<Contributor>>,
125    pub chair: Option<Vec<Contributor>>,
126    pub translator: Option<Vec<Contributor>>,
127    pub update_to: Option<Vec<Update>>,
128    /// Link to an update policy covering Crossmark updates for this work
129    pub update_policy: Option<String>,
130    /// URLs to full-text locations
131    pub link: Option<Vec<ResourceLink>>,
132    pub clinical_trial_number: Option<Vec<ClinicalTrialNumber>>,
133    /// Other identifiers for the work provided by the depositing member
134    pub alternative_id: Option<Vec<String>>,
135    /// List of references made by the work
136    pub reference: Option<Vec<Reference>>,
137    /// Information on domains that support Crossmark for this work
138    pub content_domain: Option<ContentDomain>,
139    /// Relations to other works
140    pub relation: Option<Relations>,
141    /// Peer review metadata
142    pub review: Option<Relations>,
143}
144
145/// Helper struct to represent dates in the cross ref api as nested arrays of numbers
146#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
147pub struct DateParts(pub Vec<Vec<Option<u32>>>);
148
149impl DateParts {
150    /// converts the nested array of numbers into the corresponding [DateField]
151    /// standalone years are allowed.
152    /// if an array is empty, [None] will be returned
153    pub fn as_date(&self) -> Option<DateField> {
154        /// converts an array of numbers into chrono [NaiveDate] if it contains at least a single value
155        fn naive(v: &[Option<u32>]) -> Option<NaiveDate> {
156            match v.len() {
157                0 => None,
158                1 => Some(NaiveDate::from_ymd_opt(v[0]? as i32, 1, 1)?),
159                2 => Some(NaiveDate::from_ymd_opt(v[0]? as i32, v[1]?, 1)?),
160                3 => Some(NaiveDate::from_ymd_opt(v[0]? as i32, v[1]?, v[2]?)?),
161                _ => None,
162            }
163        }
164
165        match self.0.len() {
166            0 => None,
167            1 => Some(DateField::Single(naive(&self.0[0])?)),
168            2 => Some(DateField::Range {
169                from: naive(&self.0[0])?,
170                to: naive(&self.0[1])?,
171            }),
172            _ => Some(DateField::Multi(
173                self.0
174                    .iter()
175                    .map(|x| naive(x))
176                    .collect::<Option<Vec<_>>>()?,
177            )),
178        }
179    }
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
183#[allow(missing_docs)]
184pub struct FundingBody {
185    /// Funding body primary name
186    pub name: String,
187    /// Optional [Open Funder Registry](http://www.crossref.org/fundingdata/registry.html) DOI uniquely identifing the funding body
188    #[serde(rename = "DOI")]
189    pub doi: Option<String>,
190    /// Award number(s) for awards given by the funding body
191    pub award: Option<Vec<String>>,
192    /// Either `crossref` or `publisher`
193    #[serde(rename = "doi-asserted-by")]
194    pub doi_asserted_by: Option<String>,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
198#[allow(missing_docs)]
199pub struct ClinicalTrialNumber {
200    /// Identifier of the clinical trial
201    #[serde(rename = "clinical-trial-number")]
202    pub clinical_trial_number: String,
203    /// DOI of the clinical trial regsitry that assigned the trial number
204    pub registry: String,
205    /// One of `preResults`, `results` or `postResults`
206    #[serde(rename = "type")]
207    pub type_: Option<String>,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
211#[allow(missing_docs)]
212pub struct Contributor {
213    pub family: String,
214    pub given: Option<String>,
215    /// URL-form of an [ORCID](http://orcid.org) identifier
216    #[serde(rename = "ORCID")]
217    pub orcid: Option<String>,
218    /// If true, record owner asserts that the ORCID user completed ORCID OAuth authentication
219    #[serde(rename = "authenticated-orcid")]
220    pub authenticated_orcid: Option<bool>,
221    pub affiliation: Option<Vec<Affiliation>>,
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
225#[allow(missing_docs)]
226pub struct Affiliation {
227    /// the affiliation's name
228    pub name: String,
229}
230
231/// represents full date information for an item
232#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
233#[serde(rename_all = "kebab-case")]
234pub struct Date {
235    /// Contains an ordered array of year, month, day of month.
236    /// Only year is required. Note that the field contains a nested array,
237    /// e.g. [ [ 2006, 5, 19 ] ] to conform to citeproc JSON dates
238    pub date_parts: DateParts,
239    /// Seconds since UNIX epoch
240    pub timestamp: usize,
241    /// ISO 8601 date time
242    pub date_time: String,
243}
244
245impl Date {
246    /// converts the nested array of numbers into the correct representation of chrono [NaiveDate]
247    pub fn as_date_field(&self) -> Option<DateField> {
248        self.date_parts.as_date()
249    }
250}
251
252/// represents an incomplete date only consisting of year or year and month
253#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
254pub struct PartialDate {
255    /// Contains an ordered array of year, month, day of month.
256    /// Only year is required
257    /// e.g. `[ [`2006`] ]` to conform to citeproc JSON dates
258    #[serde(rename = "date-parts")]
259    pub date_parts: DateParts,
260}
261
262impl PartialDate {
263    /// converts the nested array of numbers into the correct representation of chrono [NaiveDate]
264    pub fn as_date_field(&self) -> Option<DateField> {
265        self.date_parts.as_date()
266    }
267}
268
269/// Helper struct to capture all possible occurrences of dates in the crossref api, a nested Vec of numbers
270#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
271pub enum DateField {
272    /// only a single date vector
273    Single(NaiveDate),
274    /// two date vectors represent a range
275    Range {
276        /// start date of the range
277        from: NaiveDate,
278        /// end date of the range
279        to: NaiveDate,
280    },
281    /// more than two date vectors are present
282    Multi(Vec<NaiveDate>),
283}
284
285/// metadata about when the `Work` entry was updated
286#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
287pub struct Update {
288    /// Date on which the update was published
289    pub updated: PartialDate,
290    /// DOI of the updated work
291    #[serde(rename = "DOI")]
292    pub doi: String,
293    /// The type of update, for example retraction or correction
294    #[serde(rename = "type")]
295    pub type_: String,
296    /// A display-friendly label for the update type
297    pub label: Option<String>,
298}
299
300#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
301#[allow(missing_docs)]
302pub struct Assertion {
303    pub name: String,
304    pub value: String,
305    #[serde(rename = "URL")]
306    pub url: Option<String>,
307    pub explanation: Option<String>,
308    pub label: Option<String>,
309    pub order: Option<i32>,
310    pub group: Option<AssertionGroup>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
314#[serde(rename_all = "kebab-case")]
315#[allow(missing_docs)]
316pub struct Issue {
317    /// Date on which the work was published in print
318    pub published_print: Option<PartialDate>,
319    /// Date on which the work was published online
320    pub published_online: Option<PartialDate>,
321    /// Issue number of an article's journal
322    pub issue: Option<String>,
323}
324
325#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
326#[allow(missing_docs)]
327pub struct AssertionGroup {
328    pub name: String,
329    pub label: Option<String>,
330}
331
332#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
333#[allow(missing_docs)]
334pub struct Agency {
335    pub id: String,
336    pub label: Option<String>,
337}
338
339/// how the `Work` is licensed
340#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
341#[serde(rename_all = "kebab-case")]
342pub struct License {
343    /// Either `vor` (version of record,) `am` (accepted manuscript) or `unspecified`
344    pub content_version: String,
345    /// Number of days between the publication date of the work and the start date of this license
346    pub delay_in_days: i32,
347    /// Date on which this license begins to take effect
348    pub start: PartialDate,
349    /// Link to a web page describing this license
350    #[serde(rename = "URL")]
351    pub url: String,
352}
353
354/// metadata about a related resource
355#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
356#[serde(rename_all = "kebab-case")]
357pub struct ResourceLink {
358    /// Either `text-mining`, `similarity-checking` or `unspecified`
359    pub intended_application: String,
360    /// Either `vor` (version of record,) `am` (accepted manuscript) or `unspecified`
361    pub content_version: String,
362    /// Direct link to a full-text download location
363    #[serde(rename = "URL")]
364    pub url: String,
365    /// Content type (or MIME type) of the full-text object
366    pub content_type: Option<String>,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
370#[serde(rename_all = "kebab-case")]
371#[allow(missing_docs)]
372pub struct Reference {
373    pub key: String,
374    #[serde(rename = "DOI")]
375    pub doi: Option<String>,
376    /// One of `crossref` or `publisher`
377    pub doi_asserted_by: Option<String>,
378    pub issue: Option<String>,
379    pub first_page: Option<String>,
380    pub volume: Option<String>,
381    pub edition: Option<String>,
382    pub component: Option<String>,
383    pub standard_designator: Option<String>,
384    pub standards_body: Option<String>,
385    pub author: Option<String>,
386    pub year: Option<String>,
387    pub unstructured: Option<String>,
388    pub journal_title: Option<String>,
389    pub article_title: Option<String>,
390    pub series_title: Option<String>,
391    pub volume_title: Option<String>,
392    #[serde(rename = "ISSN")]
393    pub issn: Option<String>,
394    /// One of `pissn` or `eissn`
395    pub issn_type: Option<String>,
396    #[serde(rename = "ISBN")]
397    pub isbn: Option<String>,
398    pub isbn_type: Option<String>,
399}
400
401/// ISSN info for the `Work`
402#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
403#[serde(rename_all = "kebab-case")]
404pub struct ISSN {
405    /// identifier
406    pub value: String,
407    /// One of `eissn`, `pissn` or `lissn`
408    #[serde(rename = "type")]
409    pub type_: String,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
413#[serde(rename_all = "kebab-case")]
414#[allow(missing_docs)]
415pub struct ContentDomain {
416    pub domain: Vec<String>,
417    pub crossmark_restriction: bool,
418}
419
420#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
421#[serde(rename_all = "kebab-case")]
422#[allow(missing_docs)]
423pub struct Relation {
424    pub id_type: Option<String>,
425    pub id: Option<String>,
426    pub asserted_by: Option<String>,
427}
428
429#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
430#[serde(rename_all = "kebab-case")]
431#[allow(missing_docs)]
432pub struct Review {
433    pub running_number: Option<String>,
434    pub revision_round: Option<String>,
435    /// One of `pre-publication` or `post-publication`
436    pub stage: Option<String>,
437    /// One of `major-revision` or `minor-revision` or `reject` or `reject-with-resubmit` or `accept`
438    pub recommendation: Option<String>,
439    /// One of `referee-report` or `editor-report` or `author-comment` or `community-comment` or `aggregate`
440    #[serde(rename = "type")]
441    pub type_: String,
442    pub competing_interest_statement: Option<String>,
443    pub language: Option<String>,
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use chrono::Datelike;
450    use serde_json::*;
451    #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
452    struct Demo {
453        pub date_parts: DateParts,
454    }
455    #[test]
456    fn date_parts_serde() {
457        let demo = Demo {
458            date_parts: DateParts(vec![vec![Some(2017), Some(10), Some(11)]]),
459        };
460        let expected = r##"{"date_parts":[[2017,10,11]]}"##;
461        assert_eq!(expected, &to_string(&demo).unwrap());
462        assert_eq!(demo, from_str::<Demo>(expected).unwrap());
463    }
464
465    #[test]
466    fn date_parts_year_only() {
467        // Year-only date parts like [[2004]] should produce a valid date
468        let parts = DateParts(vec![vec![Some(2004)]]);
469        let date = parts.as_date();
470        assert!(
471            date.is_some(),
472            "Year-only DateParts should produce a valid DateField"
473        );
474        if let Some(DateField::Single(d)) = date {
475            assert_eq!(d.year(), 2004);
476        } else {
477            panic!("Expected DateField::Single");
478        }
479    }
480
481    #[test]
482    fn date_parts_year_month_only() {
483        // Year+month date parts like [[2004, 6]] should produce a valid date
484        let parts = DateParts(vec![vec![Some(2004), Some(6)]]);
485        let date = parts.as_date();
486        assert!(
487            date.is_some(),
488            "Year+month DateParts should produce a valid DateField"
489        );
490        if let Some(DateField::Single(d)) = date {
491            assert_eq!(d.year(), 2004);
492            assert_eq!(d.month(), 6);
493        } else {
494            panic!("Expected DateField::Single");
495        }
496    }
497
498    #[test]
499    fn serialize_work() {
500        let work_str = r##"{
501    "indexed": {
502      "date-parts": [
503        [
504          2019,
505          2,
506          26
507        ]
508      ],
509      "date-time": "2019-02-26T10:43:14Z",
510      "timestamp": 1551177794515
511    },
512    "reference-count": 105,
513    "publisher": "American Psychological Association (APA)",
514    "issue": "1",
515    "content-domain": {
516      "domain": [],
517      "crossmark-restriction": false
518    },
519    "short-container-title": [
520      "American Psychologist"
521    ],
522    "DOI": "10.1037/0003-066x.59.1.29",
523    "type": "journal-article",
524    "created": {
525      "date-parts": [
526        [
527          2004,
528          1,
529          21
530        ]
531      ],
532      "date-time": "2004-01-21T14:31:19Z",
533      "timestamp": 1074695479000
534    },
535    "page": "29-40",
536    "source": "Crossref",
537    "is-referenced-by-count": 84,
538    "title": [
539      "How the Mind Hurts and Heals the Body."
540    ],
541    "prefix": "10.1037",
542    "volume": "59",
543    "author": [
544      {
545        "given": "Oakley",
546        "family": "Ray",
547        "sequence": "first",
548        "affiliation": []
549      }
550    ],
551    "member": "15",
552    "published-online": {
553      "date-parts": [
554        [
555          2004
556        ]
557      ]
558    },
559    "container-title": [
560      "American Psychologist"
561    ],
562    "original-title": [],
563    "language": "en",
564    "link": [
565      {
566        "URL": "http://psycnet.apa.org/journals/amp/59/1/29.pdf",
567        "content-type": "unspecified",
568        "content-version": "vor",
569        "intended-application": "similarity-checking"
570      }
571    ],
572    "deposited": {
573      "date-parts": [
574        [
575          2018,
576          4,
577          8
578        ]
579      ],
580      "date-time": "2018-04-08T18:56:17Z",
581      "timestamp": 1523213777000
582    },
583    "score": 1,
584    "subtitle": [],
585    "short-title": [],
586    "issued": {
587      "date-parts": [
588        [
589          null
590        ]
591      ]
592    },
593    "references-count": 105,
594    "journal-issue": {
595      "published-online": {
596        "date-parts": [
597          [
598            2004
599          ]
600        ]
601      },
602      "issue": "1"
603    },
604    "alternative-id": [
605      "2004-10043-004",
606      "14736318"
607    ],
608    "URL": "http://dx.doi.org/10.1037/0003-066x.59.1.29",
609    "relation": {},
610    "ISSN": [
611      "1935-990X",
612      "0003-066X"
613    ],
614    "issn-type": [
615      {
616        "value": "0003-066X",
617        "type": "print"
618      },
619      {
620        "value": "1935-990X",
621        "type": "electronic"
622      }
623    ]
624  }
625"##;
626
627        let _work: Work = from_str(work_str).unwrap();
628    }
629}