Skip to main content

crossref/query/
works.rs

1use crate::error::Result;
2use crate::query::facet::FacetCount;
3use crate::query::types::Type;
4use crate::query::*;
5use chrono::NaiveDate;
6use std::borrow::Cow;
7#[cfg(feature = "cli")]
8use structopt::StructOpt;
9
10/// Filters allow you to narrow queries. All filter results are lists
11#[derive(Debug, Clone)]
12pub enum WorksFilter {
13    /// metadata which includes one or more funder entry
14    HasFunder,
15    /// metadata which include the `id` in FundRef data
16    Funder(String),
17    /// funder records where location = `{country name}`.
18    /// Only works on `/funders` route
19    Location(String),
20    /// metadata belonging to a DOI owner prefix `{owner_prefix}` (e.g. 10.1016 )
21    Prefix(String),
22    /// metadata belonging to a Crossref member
23    Member(String),
24    /// metadata indexed since (inclusive)
25    FromIndexDate(NaiveDate),
26    /// metadata indexed before (inclusive)
27    UntilIndexDate(NaiveDate),
28    /// metadata last (re)deposited since (inclusive)
29    FromDepositDate(NaiveDate),
30    /// metadata last (re)deposited before (inclusive)
31    UntilDepositDate(NaiveDate),
32    /// Metadata updated since (inclusive) {date}.
33    /// Currently the same as `from-deposit-date`
34    FromUpdateDate(NaiveDate),
35    /// Metadata updated before (inclusive) {date}.
36    /// Currently the same as `until-deposit-date`
37    UntilUpdateDate(NaiveDate),
38    /// metadata first deposited since (inclusive)
39    FromCreatedDate(NaiveDate),
40    /// metadata first deposited before (inclusive)
41    UntilCreatedDate(NaiveDate),
42    /// metadata where published date is since (inclusive)
43    FromPubDate(NaiveDate),
44    /// metadata where published date is before (inclusive)
45    UntilPubDate(NaiveDate),
46    /// metadata where online published date is since (inclusive)
47    FromOnlinePubDate(NaiveDate),
48    /// metadata where online published date is before (inclusive)
49    UntilOnlinePubDate(NaiveDate),
50    /// metadata where print published date is since (inclusive)
51    FromPrintPubDate(NaiveDate),
52    /// metadata where print published date is before (inclusive)
53    UntilPrintPubDate(NaiveDate),
54    /// metadata where posted date is since (inclusive)
55    FromPostedDate(NaiveDate),
56    /// metadata where posted date is before (inclusive)
57    UntilPostedDate(NaiveDate),
58    /// metadata where accepted date is since (inclusive)
59    FromAcceptedDate(NaiveDate),
60    /// metadata where accepted date is before (inclusive)
61    UntilAcceptedDate(NaiveDate),
62    /// metadata that includes any `<license_ref>` elements.
63    HasLicense,
64    /// metadata where `<license_ref> value equals the value
65    LicenseUrl(String),
66    /// metadata where the `<license_ref>`'s applies_to attribute is
67    LicenseVersion(String),
68    /// metadata where difference between publication date and the `<license_ref>`'s start_date attribute is <= value (in days)
69    LicenseDelay(i32),
70    /// metadata that includes any full text `<resource>` elements
71    HasFullText,
72    /// metadata where `<resource>` element's content_version attribute is the value
73    FullTextVersion(String),
74    /// metadata where `<resource>` element's content_type attribute is value (e.g. `application/pdf)`
75    FullTextType(String),
76    /// metadata where `<resource>` link has one of the following intended applications: `text-mining`, `similarity-checking` or `unspecified`
77    FullTextApplication(String),
78    /// metadata for works that have a list of references
79    HasReferences,
80    /// metadata for works where references are either `open`, `limited` (to Metadata Plus subscribers) or `closed`
81    ReferenceVisibility(Visibility),
82    /// metadata which include name of archive partner
83    HasArchive,
84    ///  metadata which where value of archive partner is the value
85    Archive(String),
86    /// metadata which includes one or more ORCIDs
87    HasOrcid,
88    /// metadata which includes one or more ORCIDs where the depositing publisher claims to have witness the ORCID owner authenticate with ORCID
89    HasAuthenticatedOrcid,
90    /// metadata where `<orcid>` element's value = the value
91    Orcid(String),
92    /// metadata where record has an ISSN = the value. Format is xxxx-xxxx
93    Issn(String),
94    /// metadata where record has an ISBN = the value
95    Isbn(String),
96    /// metadata records whose type = value.
97    /// Type must be an ID value from the list of types returned by the `/types` resource
98    Type(Type),
99    /// metadata records whose article or serial are mentioned in the given value.
100    /// Currently the only supported value is `doaj`
101    Directory(String),
102    /// metadata describing the DOI
103    Doi(String),
104    /// metadata for records that represent editorial updates to the DOI
105    Updates(String),
106    /// metadata for records that represent editorial updates
107    IsUpdate,
108    /// metadata for records that include a link to an editorial update policy
109    HasUpdatePolicy,
110    /// metadata for records with a publication title exactly with an exact match
111    ContainerTitle(String),
112    /// metadata for records with an exact matching category label.
113    /// Category labels come from [this list](https://www.elsevier.com/solutions/scopus/content) published by Scopus
114    CategoryName(String),
115    /// metadata for records with an exacty matching type label
116    TypeName(String),
117    /// metadata for records with a matching award number.
118    /// Optionally combine with `award.funder`
119    AwardNumber(String),
120    /// metadata for records with an award with matching funder.
121    /// Optionally combine with `award.number`
122    AwardFunder(String),
123    /// metadata for records with any assertions
124    HasAssertion,
125    /// metadata for records with an assertion in a particular group
126    AssertionGroup(String),
127    /// metadata for records with a particular named assertion
128    Assertion(String),
129    /// metadata for records that have any affiliation information
130    HasAffiliation,
131    /// metadata for records with the given alternative ID,
132    /// which may be a publisher-specific ID, or any other identifier a publisher may have provided
133    AlternativeId,
134    /// metadata for records with a given article number
135    ArticleNumber,
136    /// metadata for records which include an abstract
137    HasAbstract,
138    /// metadata for records which include a clinical trial number
139    HasClinicalTrialNumber,
140    /// metadata where the publisher records a particular domain name as the location Crossmark content will appear
141    ContentDomain(String),
142    /// metadata where the publisher records a domain name location for Crossmark content
143    HasContentDomain,
144    /// metadata where the publisher restricts Crossmark usage to content domains
145    HasDomainRestriction,
146    /// metadata for records that either assert or are the object of a relation
147    HasRelation,
148    /// One of the relation types from the Crossref relations schema
149    /// (e.g. `is-referenced-by`, `is-parent-of`, `is-preprint-of`)
150    RelationType,
151    /// Relations where the object identifier matches the identifier provided
152    RelationObject,
153    /// One of the identifier types from the Crossref relations schema (e.g. `doi`, `issn`)
154    RelationObjectType(String),
155}
156
157impl WorksFilter {
158    /// the identifier for a the query key
159    pub fn name(&self) -> &str {
160        match self {
161            WorksFilter::HasFunder => "has-funder",
162            WorksFilter::Funder(_) => "funder",
163            WorksFilter::Location(_) => "location",
164            WorksFilter::Prefix(_) => "prefix",
165            WorksFilter::Member(_) => "member",
166            WorksFilter::FromIndexDate(_) => "from-index-date",
167            WorksFilter::UntilIndexDate(_) => "until-index-date",
168            WorksFilter::FromDepositDate(_) => "from-deposit-date",
169            WorksFilter::UntilDepositDate(_) => "until-deposit-date",
170            WorksFilter::FromUpdateDate(_) => "from-update-date",
171            WorksFilter::UntilUpdateDate(_) => "until-update-date",
172            WorksFilter::FromCreatedDate(_) => "from-created-date",
173            WorksFilter::UntilCreatedDate(_) => "until-created-date",
174            WorksFilter::FromPubDate(_) => "from-pub-date",
175            WorksFilter::UntilPubDate(_) => "until-pub-date",
176            WorksFilter::FromOnlinePubDate(_) => "from-online-pub-date",
177            WorksFilter::UntilOnlinePubDate(_) => "until-online-pub-date",
178            WorksFilter::FromPrintPubDate(_) => "from-print-pub-date",
179            WorksFilter::UntilPrintPubDate(_) => "until-print-pub-date",
180            WorksFilter::FromPostedDate(_) => "from-posted-date",
181            WorksFilter::UntilPostedDate(_) => "until-posted-date",
182            WorksFilter::FromAcceptedDate(_) => "from-accepted-date",
183            WorksFilter::UntilAcceptedDate(_) => "until-accepted-date",
184            WorksFilter::HasLicense => "has-license",
185            WorksFilter::LicenseUrl(_) => "license.url",
186            WorksFilter::LicenseVersion(_) => "license.version",
187            WorksFilter::LicenseDelay(_) => "license.delay",
188            WorksFilter::HasFullText => "has-full-text",
189            WorksFilter::FullTextVersion(_) => "full-text.version",
190            WorksFilter::FullTextType(_) => "full-text.type",
191            WorksFilter::FullTextApplication(_) => "full-text.application",
192            WorksFilter::HasReferences => "has-references",
193            WorksFilter::ReferenceVisibility(_) => "reference-visibility",
194            WorksFilter::HasArchive => "has-archive",
195            WorksFilter::Archive(_) => "archive",
196            WorksFilter::HasOrcid => "has-orcid",
197            WorksFilter::HasAuthenticatedOrcid => "has-authenticated-orcid",
198            WorksFilter::Orcid(_) => "orcid",
199            WorksFilter::Issn(_) => "issn",
200            WorksFilter::Isbn(_) => "isbn",
201            WorksFilter::Type(_) => "type",
202            WorksFilter::Directory(_) => "directory",
203            WorksFilter::Doi(_) => "doi",
204            WorksFilter::Updates(_) => "updates",
205            WorksFilter::IsUpdate => "is-update",
206            WorksFilter::HasUpdatePolicy => "has-update-policy",
207            WorksFilter::ContainerTitle(_) => "container-title",
208            WorksFilter::CategoryName(_) => "category-name",
209            WorksFilter::TypeName(_) => "type-name",
210            WorksFilter::AwardNumber(_) => "award.number",
211            WorksFilter::AwardFunder(_) => "award.funder",
212            WorksFilter::HasAssertion => "has-assertion",
213            WorksFilter::AssertionGroup(_) => "assertion-group",
214            WorksFilter::Assertion(_) => "assertion",
215            WorksFilter::HasAffiliation => "has-affiliation",
216            WorksFilter::AlternativeId => "alternative-id",
217            WorksFilter::ArticleNumber => "article-number",
218            WorksFilter::HasAbstract => "has-abstract",
219            WorksFilter::HasClinicalTrialNumber => "has-clinical-trial-number",
220            WorksFilter::ContentDomain(_) => "content-domain",
221            WorksFilter::HasContentDomain => "has-content-domain",
222            WorksFilter::HasDomainRestriction => "has-domain-restriction",
223            WorksFilter::HasRelation => "has-relation",
224            WorksFilter::RelationType => "relation.type",
225            WorksFilter::RelationObject => "relation.object",
226            WorksFilter::RelationObjectType(_) => "relation.object-type",
227        }
228    }
229}
230
231impl ParamFragment for WorksFilter {
232    fn key(&self) -> Cow<'_, str> {
233        Cow::Borrowed(self.name())
234    }
235
236    fn value(&self) -> Option<Cow<'_, str>> {
237        match self {
238            WorksFilter::Funder(s)
239            | WorksFilter::Location(s)
240            | WorksFilter::Prefix(s)
241            | WorksFilter::Member(s)
242            | WorksFilter::LicenseUrl(s)
243            | WorksFilter::LicenseVersion(s)
244            | WorksFilter::FullTextVersion(s)
245            | WorksFilter::FullTextType(s)
246            | WorksFilter::FullTextApplication(s)
247            | WorksFilter::Archive(s)
248            | WorksFilter::Orcid(s)
249            | WorksFilter::Issn(s)
250            | WorksFilter::Isbn(s)
251            | WorksFilter::Directory(s)
252            | WorksFilter::Doi(s)
253            | WorksFilter::Updates(s)
254            | WorksFilter::ContainerTitle(s)
255            | WorksFilter::CategoryName(s)
256            | WorksFilter::AwardNumber(s)
257            | WorksFilter::TypeName(s)
258            | WorksFilter::AwardFunder(s)
259            | WorksFilter::AssertionGroup(s)
260            | WorksFilter::Assertion(s)
261            | WorksFilter::ContentDomain(s)
262            | WorksFilter::RelationObjectType(s) => Some(Cow::Borrowed(s.as_str())),
263            WorksFilter::ReferenceVisibility(vis) => Some(Cow::Borrowed(vis.as_str())),
264            WorksFilter::FromIndexDate(d)
265            | WorksFilter::UntilIndexDate(d)
266            | WorksFilter::FromDepositDate(d)
267            | WorksFilter::UntilDepositDate(d)
268            | WorksFilter::FromUpdateDate(d)
269            | WorksFilter::UntilUpdateDate(d)
270            | WorksFilter::FromCreatedDate(d)
271            | WorksFilter::UntilCreatedDate(d)
272            | WorksFilter::FromPubDate(d)
273            | WorksFilter::UntilPubDate(d)
274            | WorksFilter::FromOnlinePubDate(d)
275            | WorksFilter::UntilOnlinePubDate(d)
276            | WorksFilter::FromPrintPubDate(d)
277            | WorksFilter::UntilPrintPubDate(d)
278            | WorksFilter::FromPostedDate(d)
279            | WorksFilter::UntilPostedDate(d)
280            | WorksFilter::FromAcceptedDate(d)
281            | WorksFilter::UntilAcceptedDate(d) => {
282                Some(Cow::Owned(d.format("%Y-%m-%d").to_string()))
283            }
284            WorksFilter::Type(t) => Some(Cow::Borrowed(t.id())),
285            _ => Some(Cow::Borrowed("true")),
286        }
287    }
288}
289
290impl Filter for WorksFilter {}
291
292/// Field queries are available on the `/works` route and allow for queries that match only particular fields of metadata.
293#[derive(Debug, Clone)]
294#[cfg_attr(feature = "cli", derive(StructOpt))]
295pub struct FieldQuery {
296    /// match any only particular fields of metadata.
297    pub name: String,
298    /// the value of the query
299    pub value: String,
300}
301
302impl FieldQuery {
303    /// creates a new `Field` query for `title` and `subtitle`
304    pub fn title(title: &str) -> Self {
305        Self {
306            name: "title".to_string(),
307            value: title.to_string(),
308        }
309    }
310
311    /// creates a new `Field` query for `container-title` aka `publication.name`
312    pub fn container_title(container_title: &str) -> Self {
313        Self {
314            name: "container-title".to_string(),
315            value: container_title.to_string(),
316        }
317    }
318    /// creates a new `Field` query author given and family names
319    pub fn author(author: &str) -> Self {
320        Self {
321            name: "author".to_string(),
322            value: author.to_string(),
323        }
324    }
325    /// creates a new `Field` query for editor given and family names
326    pub fn editor(editor: &str) -> Self {
327        Self {
328            name: "editor".to_string(),
329            value: editor.to_string(),
330        }
331    }
332    /// creates a new `Field` query for chair given and family names
333    pub fn chair(chair: &str) -> Self {
334        Self {
335            name: "chair".to_string(),
336            value: chair.to_string(),
337        }
338    }
339    /// creates a new `Field` query for translator given and family names
340    pub fn translator(translator: &str) -> Self {
341        Self {
342            name: "translator".to_string(),
343            value: translator.to_string(),
344        }
345    }
346    /// creates a new `Field` query for author, editor, chair and translator given and family names
347    pub fn contributor(contributor: &str) -> Self {
348        Self {
349            name: "contributor".to_string(),
350            value: contributor.to_string(),
351        }
352    }
353    /// creates a new `Field` query for bibliographic information, useful for citation look up.
354    /// Includes titles, authors, ISSNs and publication years
355    pub fn bibliographic(bibliographic: &str) -> Self {
356        Self {
357            name: "bibliographic".to_string(),
358            value: bibliographic.to_string(),
359        }
360    }
361    /// creates a new `Field` query for contributor affiliations
362    pub fn affiliation(affiliation: &str) -> Self {
363        Self {
364            name: "affiliation".to_string(),
365            value: affiliation.to_string(),
366        }
367    }
368}
369
370impl CrossrefQueryParam for FieldQuery {
371    fn param_key(&self) -> Cow<'_, str> {
372        Cow::Borrowed(&self.name)
373    }
374    fn param_value(&self) -> Option<Cow<'_, str>> {
375        Some(Cow::Owned(format_query(&self.value)))
376    }
377}
378
379/// limits from where and how many `Work` items should be returned
380#[derive(Debug, Clone)]
381pub enum WorkResultControl {
382    /// use the standard ResultControl available for all components
383    Standard(ResultControl),
384    /// If you are expecting results beyond 10K, then use a cursor to deep page through the results
385    Cursor {
386        /// the cursor token provided by crossref when initially set to a value of `*`
387        token: Option<String>,
388        /// limit the results
389        rows: Option<usize>,
390    },
391}
392
393impl WorkResultControl {
394    /// set a cursor with `*` value, a new cursor will be provided in the `next-cursor` field of the result
395    pub fn new_cursor() -> Self {
396        WorkResultControl::Cursor {
397            token: None,
398            rows: None,
399        }
400    }
401
402    /// create a new Cursor with only a token value
403    pub fn cursor(token: &str) -> Self {
404        WorkResultControl::Cursor {
405            token: Some(token.to_string()),
406            rows: None,
407        }
408    }
409}
410
411impl Default for WorkResultControl {
412    fn default() -> Self {
413        WorkResultControl::new_cursor()
414    }
415}
416
417impl CrossrefQueryParam for WorkResultControl {
418    fn param_key(&self) -> Cow<'_, str> {
419        match self {
420            WorkResultControl::Standard(s) => s.param_key(),
421            WorkResultControl::Cursor { token, .. } => Cow::Owned(format!(
422                "cursor={}",
423                token.as_ref().map(String::as_str).unwrap_or("*")
424            )),
425        }
426    }
427
428    fn param_value(&self) -> Option<Cow<'_, str>> {
429        match self {
430            WorkResultControl::Standard(s) => s.param_value(),
431            WorkResultControl::Cursor { rows, .. } => {
432                rows.map(|r| Cow::Owned(format!("rows={}", r)))
433            }
434        }
435    }
436}
437///
438/// Retrieve a publication by DOI
439///
440/// # Example
441///
442/// ```edition2018
443/// use crossref::Works;
444///
445/// let works = Works::doi("10.1037/0003-066X.59.1.29");
446/// ```
447///
448/// Target the agency of a specific publication, where the str supplied is corresponded to the publication's DOI
449///
450/// # Example
451///
452/// ```edition2018
453/// use crossref::Works;
454///
455/// let works = Works::agency_for_doi("10.1037/0003-066X.59.1.29");
456/// ```
457#[derive(Debug, Clone)]
458pub enum Works {
459    /// target a Work by a specific id
460    Identifier(String),
461    /// target Works by a query
462    Query(WorksQuery),
463    /// return the registration agency for a DOI
464    Agency(String),
465}
466
467impl Works {
468    /// create a new `Works::Identifier` by converting `doi` to a `String`
469    pub fn doi(doi: &str) -> Self {
470        Works::Identifier(doi.to_string())
471    }
472    /// create a new `Works::Agency` targeting the registration agency for the DOI
473    pub fn agency_for_doi(doi: &str) -> Self {
474        Works::Agency(doi.to_string())
475    }
476}
477
478impl CrossrefRoute for Works {
479    fn route(&self) -> Result<String> {
480        match self {
481            Works::Identifier(s) => Ok(format!("{}/{}", Component::Works.route()?, s)),
482            Works::Agency(s) => Ok(format!("{}/{}/agency", Component::Works.route()?, s)),
483            Works::Query(query) => query.route(),
484        }
485    }
486}
487
488impl CrossrefQuery for Works {
489    fn resource_component(self) -> ResourceComponent {
490        ResourceComponent::Works(self)
491    }
492}
493
494/// Wraps queries that target `WorkList`, either directly or combined
495#[derive(Debug, Clone)]
496#[allow(missing_docs)]
497pub enum WorkListQuery {
498    /// Target `Works` directly
499    Works(WorksQuery),
500    /// Target the corresponding `Works` of a specific `Component`
501    Combined {
502        primary_component: Component,
503        ident: WorksIdentQuery,
504    },
505}
506
507impl WorkListQuery {
508    /// the underlying `WorksQuery`
509    pub fn query(&self) -> &WorksQuery {
510        match self {
511            WorkListQuery::Works(query) => query,
512            WorkListQuery::Combined { ident, .. } => &ident.query,
513        }
514    }
515
516    /// mut reference to the underlying `Worksquery`
517    pub fn query_mut(&mut self) -> &mut WorksQuery {
518        match self {
519            WorkListQuery::Works(query) => query,
520            WorkListQuery::Combined { ident, .. } => &mut ident.query,
521        }
522    }
523}
524
525impl From<WorksQuery> for WorkListQuery {
526    fn from(query: WorksQuery) -> WorkListQuery {
527        WorkListQuery::Works(query)
528    }
529}
530
531impl<T: ToString> From<T> for WorkListQuery {
532    fn from(term: T) -> Self {
533        WorkListQuery::Works(WorksQuery::new(term))
534    }
535}
536
537impl CrossrefRoute for WorkListQuery {
538    fn route(&self) -> Result<String> {
539        match self {
540            WorkListQuery::Works(query) => query.route(),
541            WorkListQuery::Combined {
542                primary_component,
543                ident,
544            } => Ok(format!(
545                "{}/{}{}",
546                primary_component.route()?,
547                ident.id,
548                ident.query.route()?
549            )),
550        }
551    }
552}
553
554impl CrossrefQuery for WorkListQuery {
555    fn resource_component(self) -> ResourceComponent {
556        match self {
557            WorkListQuery::Works(query) => ResourceComponent::Works(Works::Query(query)),
558            WorkListQuery::Combined {
559                primary_component,
560                ident,
561            } => match primary_component {
562                Component::Funders => ResourceComponent::Funders(Funders::Works(ident)),
563                Component::Journals => ResourceComponent::Journals(Journals::Works(ident)),
564                Component::Members => ResourceComponent::Members(Members::Works(ident)),
565                Component::Prefixes => ResourceComponent::Prefixes(Prefixes::Works(ident)),
566                Component::Types => ResourceComponent::Types(Types::Works(ident)),
567                Component::Works => ResourceComponent::Works(Works::Query(ident.query)),
568            },
569        }
570    }
571}
572
573/// Target `Works` as secondary resource component
574///
575/// # Example
576///
577/// ```edition2018
578/// use crossref::{WorksIdentQuery, WorksQuery};
579///
580/// let combined = WorksIdentQuery::new("100000015", WorksQuery::new("ontologies"));
581///
582/// ```
583/// Is equal to create a `WorksIdentQuery` from a `WorksQuery`
584///
585/// ```edition2018
586/// use crossref::WorksQuery;
587///
588/// let combined = WorksQuery::new("ontologies").into_ident("100000015");
589///
590/// ```
591/// helper struct to capture an id for a `Component` other than `/works` and an additional query for the `/works` route
592#[derive(Debug, Clone)]
593pub struct WorksIdentQuery {
594    /// the id of an component item
595    pub id: String,
596    /// the query to filter the works results
597    pub query: WorksQuery,
598}
599
600impl WorksIdentQuery {
601    /// create a new Ident Query for the `id`
602    pub fn new<T: Into<String>>(id: T, query: WorksQuery) -> Self {
603        WorksIdentQuery {
604            id: id.into(),
605            query,
606        }
607    }
608}
609
610/// Trait to determine that the type can be used in a combined query
611pub trait WorksCombiner {
612    /// the primary component of this type
613    fn primary_component() -> Component;
614
615    /// construct a new type
616    fn ident_query(ident: WorksIdentQuery) -> Self;
617
618    /// the combined crossref route
619    fn combined_route(ident: &WorksIdentQuery) -> Result<String> {
620        Ok(format!(
621            "{}/{}{}",
622            Self::primary_component().route()?,
623            ident.id,
624            ident.query.route()?
625        ))
626    }
627
628    /// create a new combined `WorkListQuery` with the primary component
629    fn work_list_query(ident: WorksIdentQuery) -> WorkListQuery {
630        WorkListQuery::Combined {
631            primary_component: Self::primary_component(),
632            ident,
633        }
634    }
635}
636
637macro_rules! impl_combiner {
638    ($($name:ident,)*) => {
639        $(
640        impl WorksCombiner for $name {
641            fn primary_component() -> Component {
642                Component::$name
643            }
644
645            fn ident_query(ident: WorksIdentQuery) -> Self {
646                $name::Works(ident)
647            }
648        }
649        )+
650    };
651}
652
653impl_combiner!(Journals, Funders, Members, Prefixes, Types,);
654
655impl WorksQuery {
656    /// alias for creating an empty default element
657    pub fn empty() -> Self {
658        WorksQuery::default()
659    }
660
661    /// creates an new `WorksQuery` with the desired sample size that will result in
662    /// a request for random dois
663    pub fn random(len: usize) -> Self {
664        WorksQuery::default().sample(len)
665    }
666
667    /// Convenience method to create a new `WorksQuery` with a term directly
668    pub fn new<T: ToString>(query: T) -> Self {
669        WorksQuery::empty().query(query)
670    }
671
672    /// add a new free form query
673    pub fn sample(mut self, len: usize) -> Self {
674        self.sample = Some(len);
675        self
676    }
677
678    /// add a new free form query
679    pub fn query<T: ToString>(mut self, query: T) -> Self {
680        self.free_form_queries.push(query.to_string());
681        self
682    }
683
684    /// Create a new query for the topics renear+ontologies
685    ///
686    /// # Example
687    ///
688    /// ```edition2018
689    /// use crossref::WorksQuery;
690    ///
691    /// let query = WorksQuery::default().queries(&["renear", "ontologies"]);
692    /// ```
693    /// add a bunch of free form query terms
694    pub fn queries<T: ToString>(mut self, queries: &[T]) -> Self {
695        self.free_form_queries
696            .extend(queries.iter().map(T::to_string));
697        self
698    }
699
700    /// add a new field query form query
701    pub fn field_query(mut self, query: FieldQuery) -> Self {
702        self.field_queries.push(query);
703        self
704    }
705
706    /// ```edition2018
707    /// use crossref::{FieldQuery,WorksQuery};
708    ///
709    /// let query = WorksQuery::default().field_queries(vec![FieldQuery::title("room at the bottom"), FieldQuery::author("richard feynman")]);
710    /// ```
711    /// add a bunch of free form query terms
712    pub fn field_queries(mut self, queries: Vec<FieldQuery>) -> Self {
713        self.field_queries.extend(queries);
714        self
715    }
716
717    /// add a new filter to the query
718    pub fn filter(mut self, filter: WorksFilter) -> Self {
719        self.filter.push(filter);
720        self
721    }
722
723    /// set sort option to the query
724    pub fn sort(mut self, sort: Sort) -> Self {
725        self.sort = Some(sort);
726        self
727    }
728
729    /// set order option to query
730    pub fn order(mut self, order: Order) -> Self {
731        self.order = Some(order);
732        self
733    }
734
735    /// add another facet to query
736    pub fn facet(mut self, facet: FacetCount) -> Self {
737        self.facets.push(facet);
738        self
739    }
740
741    /// set the cursor for result control deep paging
742    pub fn next_cursor(mut self, cursor: &str) -> Self {
743        let rows = match self.result_control {
744            Some(WorkResultControl::Standard(ResultControl::Rows(rows))) => Some(rows),
745            _ => None,
746        };
747        self.result_control = Some(WorkResultControl::Cursor {
748            token: Some(cursor.to_string()),
749            rows,
750        });
751        self
752    }
753
754    /// set an empty cursor
755    pub fn new_cursor(mut self) -> Self {
756        self.result_control = Some(WorkResultControl::new_cursor());
757        self
758    }
759    /// set result control option to query
760    pub fn result_control(mut self, result_control: WorkResultControl) -> Self {
761        self.result_control = Some(result_control);
762        self
763    }
764
765    /// Wrap the query in a combined query.
766    ///
767    /// # Example
768    /// Create a Funders Query that targets all works of a funder with id `funder id`.
769    ///
770    /// ```edition2018
771    /// # use crossref::{WorksQuery, Funders};
772    /// let funders: Funders = WorksQuery::default().into_combined("funder id");
773    /// ```
774    pub fn into_combined<W: WorksCombiner>(self, id: &str) -> W {
775        W::ident_query(self.into_ident(id))
776    }
777
778    /// Bind the query to a specific id of a primary endpoint element
779    pub fn into_ident(self, id: &str) -> WorksIdentQuery {
780        WorksIdentQuery::new(id, self)
781    }
782
783    /// wrap this query in new `WorkListQuery` that targets the `/works` route of a primary component with an id.
784    /// The query will evaluate to the same as [`into_combined`]
785    ///
786    /// # Example
787    ///
788    /// Create a query that targets all `Works` of a funder with id `funder id`
789    ///
790    /// ```edition2018
791    /// # use crossref::{WorksQuery, Funders};
792    /// let query = WorksQuery::default()
793    ///     .into_combined_query::<Funders>("funder id");
794    ///
795    /// ```
796    pub fn into_combined_query<W: WorksCombiner>(self, id: &str) -> WorkListQuery {
797        W::work_list_query(self.into_ident(id))
798    }
799}
800
801/// Used to construct a query that targets crossref `Works` elements
802///
803/// # Example
804///
805/// ```edition2018
806/// use crossref::{Order, WorksQuery};
807///
808/// // create a new query for topcis machine+learning ordered desc
809/// let query = WorksQuery::new("machine learning").order(Order::Desc);
810/// ```
811///
812/// Each query parameter is ANDed
813#[derive(Debug, Clone, Default)]
814pub struct WorksQuery {
815    /// search by non specific query
816    pub free_form_queries: Vec<String>,
817    /// match only particular fields of metadata
818    pub field_queries: Vec<FieldQuery>,
819    /// filter to apply while querying
820    pub filter: Vec<WorksFilter>,
821    /// sort results by a certain field and
822    pub sort: Option<Sort>,
823    /// set the sort order to `asc` or `desc`
824    pub order: Option<Order>,
825    /// enable facet information in responses
826    pub facets: Vec<FacetCount>,
827    /// deep page through `/works` result sets
828    pub result_control: Option<WorkResultControl>,
829    /// request random dois
830    /// if set all other parameters are ignored
831    pub sample: Option<usize>,
832}
833
834impl CrossrefRoute for WorksQuery {
835    fn route(&self) -> Result<String> {
836        let mut params = Vec::new();
837
838        if let Some(sample) = self.sample {
839            return Ok(format!("sample={}", sample));
840        }
841
842        if !self.free_form_queries.is_empty() {
843            params.push(Cow::Owned(format!(
844                "query={}",
845                format_queries(&self.free_form_queries)
846            )));
847        }
848        if !self.field_queries.is_empty() {
849            params.extend(self.field_queries.iter().map(CrossrefQueryParam::param))
850        }
851        if !self.filter.is_empty() {
852            params.push(self.filter.param());
853        }
854        if !self.facets.is_empty() {
855            params.push(self.facets.param());
856        }
857        if let Some(sort) = &self.sort {
858            params.push(sort.param());
859        }
860        if let Some(order) = &self.order {
861            params.push(order.param());
862        }
863        if let Some(rc) = &self.result_control {
864            params.push(rc.param());
865        }
866
867        Ok(format!(
868            "{}?{}",
869            Component::Works.route()?,
870            params.join("&")
871        ))
872    }
873}
874
875impl CrossrefParams for WorksQuery {
876    type Filter = WorksFilter;
877
878    fn query_terms(&self) -> &[String] {
879        &self.free_form_queries
880    }
881    fn filters(&self) -> &[Self::Filter] {
882        &self.filter
883    }
884    fn sort(&self) -> Option<&Sort> {
885        self.sort.as_ref()
886    }
887    fn order(&self) -> Option<&Order> {
888        self.order.as_ref()
889    }
890    fn facets(&self) -> &[FacetCount] {
891        &self.facets
892    }
893    fn result_control(&self) -> Option<&ResultControl> {
894        if let Some(WorkResultControl::Standard(ref std)) = self.result_control {
895            Some(std)
896        } else {
897            None
898        }
899    }
900}
901
902#[cfg(test)]
903mod tests {
904    use super::*;
905
906    #[test]
907    fn serialize_works_ident() {
908        let works = Works::doi("10.1037/0003-066X.59.1.29");
909
910        assert_eq!("/works/10.1037/0003-066X.59.1.29", &works.route().unwrap())
911    }
912
913    #[test]
914    fn filter_names_have_no_whitespace() {
915        // Ensure no filter name contains trailing whitespace (e.g. tab characters)
916        let filters = vec![
917            WorksFilter::HasFunder,
918            WorksFilter::HasLicense,
919            WorksFilter::HasFullText,
920            WorksFilter::HasReferences,
921            WorksFilter::HasArchive,
922            WorksFilter::HasOrcid,
923            WorksFilter::HasAuthenticatedOrcid,
924            WorksFilter::IsUpdate,
925            WorksFilter::HasUpdatePolicy,
926            WorksFilter::HasAssertion,
927            WorksFilter::HasAffiliation,
928            WorksFilter::AlternativeId,
929            WorksFilter::ArticleNumber,
930            WorksFilter::HasAbstract,
931            WorksFilter::HasClinicalTrialNumber,
932            WorksFilter::HasContentDomain,
933            WorksFilter::HasDomainRestriction,
934            WorksFilter::HasRelation,
935            WorksFilter::RelationType,
936            WorksFilter::RelationObject,
937        ];
938        for f in &filters {
939            let name = f.name();
940            assert_eq!(
941                name,
942                name.trim(),
943                "Filter name {:?} contains leading/trailing whitespace",
944                name
945            );
946        }
947    }
948}