Skip to main content

crossref_client/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
8define_keyed_enum! {
9/// A field of a [`Work`](crate::Work) that a query can ask crossref to return.
10///
11/// Passed to [`WorksQuery::elements`]; crossref returns only what was selected,
12/// so every field left out is [`None`] on the resulting `Work`. Covers all 59
13/// fields `/works` accepts, which `every_selectable_element_is_accepted_by_the_api`
14/// pins against what the api reports.
15WorkElement {
16    DOI => "DOI",
17    ISBN => "ISBN",
18    ISSN => "ISSN",
19    URL => "URL",
20    Abstract_ => "abstract",
21    Accepted => "accepted",
22    AlternativeId => "alternative-id",
23    Approved => "approved",
24    Archive => "archive",
25    ArticleNumber => "article-number",
26    Assertion => "assertion",
27    Author => "author",
28    Chair => "chair",
29    ClinicalTrialNumber => "clinical-trial-number",
30    ContainerTitle => "container-title",
31    ContentCreated => "content-created",
32    ContentDomain => "content-domain",
33    Contributor => "contributor",
34    Created => "created",
35    Degree => "degree",
36    Deposited => "deposited",
37    Editor => "editor",
38    Event => "event",
39    Funder => "funder",
40    GroupTitle => "group-title",
41    Indexed => "indexed",
42    IsReferencedByCount => "is-referenced-by-count",
43    IssnType => "issn-type",
44    Issue => "issue",
45    Issued => "issued",
46    License => "license",
47    Link => "link",
48    Member => "member",
49    OriginalTitle => "original-title",
50    Page => "page",
51    Posted => "posted",
52    Prefix => "prefix",
53    Published => "published",
54    PublishedOnline => "published-online",
55    PublishedPrint => "published-print",
56    Publisher => "publisher",
57    PublisherLocation => "publisher-location",
58    Reference => "reference",
59    ReferencesCount => "references-count",
60    Relation => "relation",
61    Resource => "resource",
62    Score => "score",
63    ShortContainerTitle => "short-container-title",
64    ShortTitle => "short-title",
65    StandardsBody => "standards-body",
66    Subject => "subject",
67    Subtitle => "subtitle",
68    Title => "title",
69    Translator => "translator",
70    Type => "type",
71    UpdatePolicy => "update-policy",
72    UpdateTo => "update-to",
73    UpdatedBy => "updated-by",
74    Volume => "volume",
75}
76}
77
78define_filter! {
79/// Narrows a `/works` query. Every filter is ANDed with the others.
80///
81/// Covers all 90 filters `/works` accepts; crossref answers an unrecognised
82/// one with [`Error::ValidationFailure`](crate::Error::ValidationFailure)
83/// naming the ones it does know, which is what
84/// `every_works_filter_is_accepted_by_the_api` pins this list against.
85///
86/// Note that `location` and `reference-visibility` are *not* among them --
87/// `location` belongs to [`FundersFilter`](crate::query::funders::FundersFilter).
88///
89/// A value carrying a `,` cannot be sent at all, whatever the filter: crossref
90/// splits the `filter` parameter on it after decoding, so the query is refused
91/// with [`Error::UnsendableFilterValue`](crate::Error::UnsendableFilterValue).
92WorksFilter;
93markers {
94    /// metadata which includes one or more funder entry
95    HasFunder => "has-funder",
96    /// metadata where a funder entry carries a Funder Registry DOI
97    HasFunderDoi => "has-funder-doi",
98    /// metadata where a funder entry carries a ROR id
99    HasFunderRorId => "has-funder-ror-id",
100    /// metadata for records that have any affiliation information
101    HasAffiliation => "has-affiliation",
102    /// metadata where an affiliation carries a ROR id
103    HasAffiliationRorId => "has-affiliation-ror-id",
104    /// metadata carrying a ROR id anywhere
105    HasRorId => "has-ror-id",
106    /// metadata that includes any `<license_ref>` elements
107    HasLicense => "has-license",
108    /// metadata that includes any full text `<resource>` elements
109    HasFullText => "has-full-text",
110    /// metadata for works that have a list of references
111    HasReferences => "has-references",
112    /// metadata which include name of archive partner
113    HasArchive => "has-archive",
114    /// metadata which includes one or more ORCIDs
115    HasOrcid => "has-orcid",
116    /// metadata which includes one or more ORCIDs where the depositing publisher claims to have witness the ORCID owner authenticate with ORCID
117    HasAuthenticatedOrcid => "has-authenticated-orcid",
118    /// metadata for records which include an abstract
119    HasAbstract => "has-abstract",
120    /// metadata for records which include a clinical trial number
121    HasClinicalTrialNumber => "has-clinical-trial-number",
122    /// metadata where the publisher records a domain name location for Crossmark content
123    HasContentDomain => "has-content-domain",
124    /// metadata where the publisher restricts Crossmark usage to content domains
125    HasDomainRestriction => "has-domain-restriction",
126    /// metadata for records that either assert or are the object of a relation
127    HasRelation => "has-relation",
128    /// metadata for records that carry an editorial update
129    HasUpdate => "has-update",
130    /// metadata for records that include a link to an editorial update policy
131    HasUpdatePolicy => "has-update-policy",
132    /// metadata for records with any assertions
133    HasAssertion => "has-assertion",
134    /// metadata for records that carry award information
135    HasAward => "has-award",
136    /// metadata for records deposited under more than one DOI
137    HasAlias => "has-alias",
138    /// metadata for records that are the primary DOI of an alias group
139    HasPrimeDoi => "has-prime-doi",
140    /// metadata for records that describe an event
141    HasEvent => "has-event",
142    /// metadata for records that represent editorial updates
143    IsUpdate => "is-update",
144}
145values {
146    /// metadata which include the `id` in FundRef data
147    Funder(String) => "funder",
148    /// metadata belonging to a DOI owner prefix `{owner_prefix}` (e.g. 10.1016 )
149    Prefix(String) => "prefix",
150    /// metadata belonging to a Crossref member
151    Member(String) => "member",
152    /// metadata describing the DOI
153    Doi(String) => "doi",
154    /// metadata where record has an ISSN = the value. Format is xxxx-xxxx
155    Issn(String) => "issn",
156    /// metadata where record has an ISBN = the value
157    Isbn(String) => "isbn",
158    /// metadata where `<orcid>` element's value = the value
159    Orcid(String) => "orcid",
160    ///  metadata which where value of archive partner is the value
161    Archive(String) => "archive",
162    /// metadata records whose article or serial are mentioned in the given value.
163    /// Currently the only supported value is `doaj`
164    Directory(String) => "directory",
165    /// metadata for records that represent editorial updates to the DOI
166    Updates(String) => "updates",
167    /// metadata for records with a publication title exactly with an exact match
168    ContainerTitle(String) => "container-title",
169    /// metadata for records with an exact matching category label.
170    /// Category labels come from [this list](https://www.elsevier.com/solutions/scopus/content) published by Scopus
171    CategoryName(String) => "category-name",
172    /// metadata for records with an exacty matching type label
173    TypeName(String) => "type-name",
174    /// metadata records whose type = value.
175    /// Type must be an ID value from the list of types returned by the `/types` resource
176    Type(Type) => "type",
177    /// metadata for records with a matching group title, as deposited for posted content
178    GroupTitle(String) => "group-title",
179    /// metadata where the publisher records a particular domain name as the location Crossmark content will appear
180    ContentDomain(String) => "content-domain",
181    /// metadata for records carrying the given clinical trial number
182    ClinicalTrialNumber(String) => "clinical-trial-number",
183    /// metadata for records with the given alternative ID,
184    /// which may be a publisher-specific ID, or any other identifier a publisher may have provided
185    AlternativeId(String) => "alternative-id",
186    /// metadata for records with a given article number
187    ArticleNumber(String) => "article-number",
188    /// metadata carrying the given [ROR](https://ror.org) id, the identifier
189    /// crossref now models affiliations and funders with
190    RorId(String) => "ror-id",
191    /// metadata for editorial updates of the given kind, e.g. `correction` or `retraction`
192    UpdateType(String) => "update-type",
193    /// metadata where a funder's DOI was asserted by the value, either
194    /// `crossref` or `publisher`
195    FunderDoiAssertedBy(String) => "funder-doi-asserted-by",
196    /// metadata for records with a particular named assertion
197    Assertion(String) => "assertion",
198    /// metadata for records with an assertion in a particular group
199    AssertionGroup(String) => "assertion-group",
200    /// metadata for records with a matching award number.
201    /// Optionally combine with `award.funder`
202    AwardNumber(String) => "award.number",
203    /// metadata for records with an award with matching funder.
204    /// Optionally combine with `award.number`
205    AwardFunder(String) => "award.funder",
206    /// metadata for records with an award of at least this amount
207    GteAwardAmount(u64) => "gte-award-amount",
208    /// metadata for records with an award of at most this amount
209    LteAwardAmount(u64) => "lte-award-amount",
210    /// metadata where `<license_ref>` value equals the value
211    LicenseUrl(String) => "license.url",
212    /// metadata where the `<license_ref>`'s applies_to attribute is
213    LicenseVersion(String) => "license.version",
214    /// metadata where difference between publication date and the `<license_ref>`'s start_date attribute is <= value (in days)
215    LicenseDelay(i32) => "license.delay",
216    /// metadata where `<resource>` element's content_version attribute is the value
217    FullTextVersion(String) => "full-text.version",
218    /// metadata where `<resource>` element's content_type attribute is value (e.g. `application/pdf)`
219    FullTextType(String) => "full-text.type",
220    /// metadata where `<resource>` link has one of the following intended applications: `text-mining`, `similarity-checking` or `unspecified`
221    FullTextApplication(String) => "full-text.application",
222    /// One of the relation types from the Crossref relations schema
223    /// (e.g. `is-referenced-by`, `is-parent-of`, `is-preprint-of`)
224    RelationType(String) => "relation.type",
225    /// Relations where the object identifier matches the identifier provided
226    RelationObject(String) => "relation.object",
227    /// One of the identifier types from the Crossref relations schema (e.g. `doi`, `issn`)
228    RelationObjectType(String) => "relation.object-type",
229    /// metadata indexed since (inclusive)
230    FromIndexDate(NaiveDate) => "from-index-date",
231    /// metadata indexed before (inclusive)
232    UntilIndexDate(NaiveDate) => "until-index-date",
233    /// metadata last (re)deposited since (inclusive)
234    FromDepositDate(NaiveDate) => "from-deposit-date",
235    /// metadata last (re)deposited before (inclusive)
236    UntilDepositDate(NaiveDate) => "until-deposit-date",
237    /// Metadata updated since (inclusive) {date}.
238    /// Currently the same as `from-deposit-date`
239    FromUpdateDate(NaiveDate) => "from-update-date",
240    /// Metadata updated before (inclusive) {date}.
241    /// Currently the same as `until-deposit-date`
242    UntilUpdateDate(NaiveDate) => "until-update-date",
243    /// metadata first deposited since (inclusive)
244    FromCreatedDate(NaiveDate) => "from-created-date",
245    /// metadata first deposited before (inclusive)
246    UntilCreatedDate(NaiveDate) => "until-created-date",
247    /// metadata where published date is since (inclusive)
248    FromPubDate(NaiveDate) => "from-pub-date",
249    /// metadata where published date is before (inclusive)
250    UntilPubDate(NaiveDate) => "until-pub-date",
251    /// metadata where online published date is since (inclusive)
252    FromOnlinePubDate(NaiveDate) => "from-online-pub-date",
253    /// metadata where online published date is before (inclusive)
254    UntilOnlinePubDate(NaiveDate) => "until-online-pub-date",
255    /// metadata where print published date is since (inclusive)
256    FromPrintPubDate(NaiveDate) => "from-print-pub-date",
257    /// metadata where print published date is before (inclusive)
258    UntilPrintPubDate(NaiveDate) => "until-print-pub-date",
259    /// metadata where posted date is since (inclusive)
260    FromPostedDate(NaiveDate) => "from-posted-date",
261    /// metadata where posted date is before (inclusive)
262    UntilPostedDate(NaiveDate) => "until-posted-date",
263    /// metadata where accepted date is since (inclusive)
264    FromAcceptedDate(NaiveDate) => "from-accepted-date",
265    /// metadata where accepted date is before (inclusive)
266    UntilAcceptedDate(NaiveDate) => "until-accepted-date",
267    /// metadata where approved date is since (inclusive)
268    FromApprovedDate(NaiveDate) => "from-approved-date",
269    /// metadata where approved date is before (inclusive)
270    UntilApprovedDate(NaiveDate) => "until-approved-date",
271    /// metadata where an award was made since (inclusive)
272    FromAwardedDate(NaiveDate) => "from-awarded-date",
273    /// metadata where an award was made before (inclusive)
274    UntilAwardedDate(NaiveDate) => "until-awarded-date",
275    /// metadata where issued date is since (inclusive)
276    FromIssuedDate(NaiveDate) => "from-issued-date",
277    /// metadata where issued date is before (inclusive)
278    UntilIssuedDate(NaiveDate) => "until-issued-date",
279    /// metadata for events starting since (inclusive)
280    FromEventStartDate(NaiveDate) => "from-event-start-date",
281    /// metadata for events starting before (inclusive)
282    UntilEventStartDate(NaiveDate) => "until-event-start-date",
283    /// metadata for events ending since (inclusive)
284    FromEventEndDate(NaiveDate) => "from-event-end-date",
285    /// metadata for events ending before (inclusive)
286    UntilEventEndDate(NaiveDate) => "until-event-end-date",
287}
288}
289
290define_field_queries! {
291    /// titles, including the subtitle
292    Title => "title" / title,
293    /// the title of the containing work, aka `publication.name`
294    ContainerTitle => "container-title" / container_title,
295    /// author given and family names
296    Author => "author" / author,
297    /// editor given and family names
298    Editor => "editor" / editor,
299    /// chair given and family names
300    Chair => "chair" / chair,
301    /// translator given and family names
302    Translator => "translator" / translator,
303    /// author, editor, chair and translator given and family names
304    Contributor => "contributor" / contributor,
305    /// bibliographic information, useful for citation look up. Includes
306    /// titles, authors, ISSNs and publication years
307    Bibliographic => "bibliographic" / bibliographic,
308    /// contributor affiliations
309    Affiliation => "affiliation" / affiliation,
310    /// the degree a dissertation was awarded for
311    Degree => "degree" / degree,
312    /// the description deposited for posted content
313    Description => "description" / description,
314    /// the short form of an event's name
315    EventAcronym => "event-acronym" / event_acronym,
316    /// where an event was held
317    EventLocation => "event-location" / event_location,
318    /// an event's name
319    EventName => "event-name" / event_name,
320    /// who sponsored an event
321    EventSponsor => "event-sponsor" / event_sponsor,
322    /// an event's theme
323    EventTheme => "event-theme" / event_theme,
324    /// the name of a funding body, for works whose funder carries no registry DOI
325    FunderName => "funder-name" / funder_name,
326    /// where the publisher is located
327    PublisherLocation => "publisher-location" / publisher_location,
328    /// the publisher's name
329    PublisherName => "publisher-name" / publisher_name,
330    /// the short form of a standards body's name
331    StandardsBodyAcronym => "standards-body-acronym" / standards_body_acronym,
332    /// the name of the body that issued a standard
333    StandardsBodyName => "standards-body-name" / standards_body_name,
334}
335
336impl CrossrefQueryParam for FieldQuery {
337    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
338        vec![(
339            Cow::Borrowed(self.name()),
340            Cow::Owned(format_query(self.value())),
341        )]
342    }
343}
344
345/// limits from where and how many `Work` items should be returned
346#[derive(Debug, Clone)]
347pub enum WorkResultControl {
348    /// use the standard ResultControl available for all components
349    Standard(ResultControl),
350    /// If you are expecting results beyond 10K, then use a cursor to deep page through the results
351    Cursor {
352        /// the cursor token provided by crossref when initially set to a value of `*`
353        token: Option<String>,
354        /// limit the results
355        rows: Option<usize>,
356    },
357}
358
359impl WorkResultControl {
360    /// set a cursor with `*` value, a new cursor will be provided in the `next-cursor` field of the result
361    pub fn new_cursor() -> Self {
362        WorkResultControl::Cursor {
363            token: None,
364            rows: None,
365        }
366    }
367
368    /// create a new Cursor with only a token value
369    pub fn cursor(token: &str) -> Self {
370        WorkResultControl::Cursor {
371            token: Some(token.to_string()),
372            rows: None,
373        }
374    }
375}
376
377impl Default for WorkResultControl {
378    fn default() -> Self {
379        WorkResultControl::new_cursor()
380    }
381}
382
383impl CrossrefQueryParam for WorkResultControl {
384    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
385        match self {
386            WorkResultControl::Standard(standard) => standard.params(),
387            WorkResultControl::Cursor { token, rows } => {
388                let mut params = vec![(
389                    Cow::Borrowed("cursor"),
390                    Cow::Borrowed(token.as_deref().unwrap_or("*")),
391                )];
392                if let Some(rows) = rows {
393                    params.push((Cow::Borrowed("rows"), Cow::Owned(rows.to_string())));
394                }
395                params
396            }
397        }
398    }
399}
400///
401/// Retrieve a publication by DOI
402///
403/// # Example
404///
405/// ```no_run
406/// use crossref_client::Works;
407///
408/// let works = Works::doi("10.1037/0003-066X.59.1.29");
409/// ```
410///
411/// Target the agency of a specific publication, where the str supplied is corresponded to the publication's DOI
412///
413/// # Example
414///
415/// ```no_run
416/// use crossref_client::Works;
417///
418/// let works = Works::agency_for_doi("10.1037/0003-066X.59.1.29");
419/// ```
420#[derive(Debug, Clone)]
421pub enum Works {
422    /// target a Work by a specific id
423    Identifier(String),
424    /// target Works by a query
425    Query(WorksQuery),
426    /// return the registration agency for a DOI
427    Agency(String),
428}
429
430impl Works {
431    /// create a new `Works::Identifier` by converting `doi` to a `String`
432    pub fn doi(doi: &str) -> Self {
433        Works::Identifier(doi.to_string())
434    }
435    /// create a new `Works::Agency` targeting the registration agency for the DOI
436    pub fn agency_for_doi(doi: &str) -> Self {
437        Works::Agency(doi.to_string())
438    }
439}
440
441impl CrossrefRoute for Works {
442    fn route(&self) -> Result<String> {
443        match self {
444            Works::Identifier(s) => Ok(format!("{}/{}", Component::Works.route()?, s)),
445            Works::Agency(s) => Ok(format!("{}/{}/agency", Component::Works.route()?, s)),
446            Works::Query(query) => query.route(),
447        }
448    }
449}
450
451impl CrossrefQuery for Works {
452    fn resource_component(self) -> ResourceComponent {
453        ResourceComponent::Works(self)
454    }
455}
456
457/// Wraps queries that target `WorkList`, either directly or combined
458#[derive(Debug, Clone)]
459pub enum WorkListQuery {
460    /// Target `Works` directly
461    Works(WorksQuery),
462    /// Target the corresponding `Works` of a specific `Component`
463    Combined {
464        /// the component whose works are being targeted
465        primary_component: WorksComponent,
466        /// the component id, and the query to narrow its works with
467        ident: WorksIdentQuery,
468    },
469}
470
471impl WorkListQuery {
472    /// the underlying `WorksQuery`
473    pub fn query(&self) -> &WorksQuery {
474        match self {
475            WorkListQuery::Works(query) => query,
476            WorkListQuery::Combined { ident, .. } => &ident.query,
477        }
478    }
479
480    /// mut reference to the underlying `Worksquery`
481    pub fn query_mut(&mut self) -> &mut WorksQuery {
482        match self {
483            WorkListQuery::Works(query) => query,
484            WorkListQuery::Combined { ident, .. } => &mut ident.query,
485        }
486    }
487}
488
489impl From<WorksQuery> for WorkListQuery {
490    fn from(val: WorksQuery) -> Self {
491        WorkListQuery::Works(val)
492    }
493}
494
495impl<T: ToString> From<T> for WorkListQuery {
496    fn from(term: T) -> Self {
497        WorkListQuery::Works(WorksQuery::new(term))
498    }
499}
500
501impl CrossrefRoute for WorkListQuery {
502    fn route(&self) -> Result<String> {
503        match self {
504            WorkListQuery::Works(query) => query.route(),
505            WorkListQuery::Combined {
506                primary_component,
507                ident,
508            } => Ok(format!(
509                "{}/{}{}",
510                primary_component.route()?,
511                ident.id,
512                ident.query.route()?
513            )),
514        }
515    }
516}
517
518impl CrossrefQuery for WorkListQuery {
519    fn resource_component(self) -> ResourceComponent {
520        match self {
521            WorkListQuery::Works(query) => ResourceComponent::Works(Works::Query(query)),
522            WorkListQuery::Combined {
523                primary_component,
524                ident,
525            } => match primary_component {
526                WorksComponent::Funders => ResourceComponent::Funders(Funders::Works(ident)),
527                WorksComponent::Journals => ResourceComponent::Journals(Journals::Works(ident)),
528                WorksComponent::Members => ResourceComponent::Members(Members::Works(ident)),
529                WorksComponent::Prefixes => ResourceComponent::Prefixes(Prefixes::Works(ident)),
530                WorksComponent::Types => ResourceComponent::Types(Types::Works(ident)),
531            },
532        }
533    }
534}
535
536/// Target `Works` as secondary resource component
537///
538/// # Example
539///
540/// ```no_run
541/// use crossref_client::{WorksIdentQuery, WorksQuery};
542///
543/// let combined = WorksIdentQuery::new("100000015", WorksQuery::new("ontologies"));
544///
545/// ```
546/// Is equal to create a `WorksIdentQuery` from a `WorksQuery`
547///
548/// ```no_run
549/// use crossref_client::WorksQuery;
550///
551/// let combined = WorksQuery::new("ontologies").into_ident("100000015");
552///
553/// ```
554/// helper struct to capture an id for a `Component` other than `/works` and an additional query for the `/works` route
555#[derive(Debug, Clone)]
556pub struct WorksIdentQuery {
557    /// the id of an component item
558    pub id: String,
559    /// the query to filter the works results
560    pub query: WorksQuery,
561}
562
563impl WorksIdentQuery {
564    /// create a new Ident Query for the `id`
565    pub fn new<T: Into<String>>(id: T, query: WorksQuery) -> Self {
566        WorksIdentQuery {
567            id: id.into(),
568            query,
569        }
570    }
571}
572
573/// Trait to determine that the type can be used in a combined query
574pub trait WorksCombiner {
575    /// the primary component of this type
576    fn primary_component() -> WorksComponent;
577
578    /// construct a new type
579    fn ident_query(ident: WorksIdentQuery) -> Self;
580
581    /// the combined crossref route
582    fn combined_route(ident: &WorksIdentQuery) -> Result<String> {
583        Ok(format!(
584            "{}/{}{}",
585            Self::primary_component().route()?,
586            ident.id,
587            ident.query.route()?
588        ))
589    }
590
591    /// create a new combined `WorkListQuery` with the primary component
592    fn work_list_query(ident: WorksIdentQuery) -> WorkListQuery {
593        WorkListQuery::Combined {
594            primary_component: Self::primary_component(),
595            ident,
596        }
597    }
598}
599
600macro_rules! impl_combiner {
601    ($($name:ident,)*) => {
602        $(
603        impl WorksCombiner for $name {
604            fn primary_component() -> WorksComponent {
605                WorksComponent::$name
606            }
607
608            fn ident_query(ident: WorksIdentQuery) -> Self {
609                $name::Works(ident)
610            }
611        }
612        )+
613    };
614}
615
616impl_combiner!(Journals, Funders, Members, Prefixes, Types,);
617
618impl WorksQuery {
619    /// alias for creating an empty default element
620    pub fn empty() -> Self {
621        WorksQuery::default()
622    }
623
624    /// creates an new `WorksQuery` with the desired sample size that will result in
625    /// a request for random dois
626    pub fn random(len: usize) -> Self {
627        WorksQuery::default().sample(len)
628    }
629
630    /// Convenience method to create a new `WorksQuery` with a term directly
631    pub fn new<T: ToString>(query: T) -> Self {
632        WorksQuery::empty().query(query)
633    }
634
635    /// Ask for `len` random works instead of a search, or for a search if
636    /// given [`None`]. Crossref ignores every other parameter when it is set.
637    pub fn sample(mut self, len: impl Into<Option<usize>>) -> Self {
638        self.sample = len.into();
639        self
640    }
641
642    /// add a new free form query
643    pub fn query<T: ToString>(mut self, query: T) -> Self {
644        self.free_form_queries.push(query.to_string());
645        self
646    }
647
648    /// Create a new query for the topics renear+ontologies
649    ///
650    /// # Example
651    ///
652    /// ```no_run
653    /// use crossref_client::WorksQuery;
654    ///
655    /// let query = WorksQuery::default().queries(&["renear", "ontologies"]);
656    /// ```
657    /// add a bunch of free form query terms
658    pub fn queries<T: ToString>(mut self, queries: &[T]) -> Self {
659        self.free_form_queries
660            .extend(queries.iter().map(T::to_string));
661        self
662    }
663
664    /// add a new field query form query
665    pub fn field_query(mut self, query: FieldQuery) -> Self {
666        self.field_queries.push(query);
667        self
668    }
669
670    /// Narrow the response to the given fields.
671    ///
672    /// Crossref returns only what is selected, so every field left out is
673    /// [`None`] on the resulting [`Work`](crate::Work).
674    ///
675    /// [`WorkElement::DOI`] is always sent, whether or not it is asked for: it
676    /// is the one field [`Work`](crate::Work) requires, so a response without
677    /// it could not be read back at all.
678    pub fn elements(mut self, element: Vec<WorkElement>) -> Self {
679        self.elements.extend(element);
680        self
681    }
682
683    /// ```no_run
684    /// use crossref_client::{FieldQuery,WorksQuery};
685    ///
686    /// let query = WorksQuery::default().field_queries(vec![FieldQuery::title("room at the bottom"), FieldQuery::author("richard feynman")]);
687    /// ```
688    /// add a bunch of free form query terms
689    pub fn field_queries(mut self, queries: Vec<FieldQuery>) -> Self {
690        self.field_queries.extend(queries);
691        self
692    }
693
694    /// add a new filter to the query
695    pub fn filter(mut self, filter: WorksFilter) -> Self {
696        self.filter.push(filter);
697        self
698    }
699
700    /// Sort the results by a field, or by relevance if given [`None`].
701    pub fn sort(mut self, sort: impl Into<Option<Sort>>) -> Self {
702        self.sort = sort.into();
703        self
704    }
705
706    /// Order the results, or leave the order to crossref if given [`None`].
707    pub fn order(mut self, order: impl Into<Option<Order>>) -> Self {
708        self.order = order.into();
709        self
710    }
711
712    /// add another facet to query
713    pub fn facet(mut self, facet: FacetCount) -> Self {
714        self.facets.push(facet);
715        self
716    }
717
718    /// set the cursor for result control deep paging
719    pub fn next_cursor(mut self, cursor: &str) -> Self {
720        let rows = match self.result_control {
721            Some(WorkResultControl::Standard(ResultControl::Rows(rows))) => Some(rows),
722            _ => None,
723        };
724        self.result_control = Some(WorkResultControl::Cursor {
725            token: Some(cursor.to_string()),
726            rows,
727        });
728        self
729    }
730
731    /// set an empty cursor
732    pub fn new_cursor(mut self) -> Self {
733        self.result_control = Some(WorkResultControl::new_cursor());
734        self
735    }
736    /// Limit the results, or take crossref's default page if given [`None`].
737    pub fn result_control(mut self, result_control: impl Into<Option<WorkResultControl>>) -> Self {
738        self.result_control = result_control.into();
739        self
740    }
741
742    /// Wrap the query in a combined query.
743    ///
744    /// # Example
745    /// Create a Funders Query that targets all works of a funder with id `funder id`.
746    ///
747    /// ```no_run
748    /// # use crossref_client::{WorksQuery, Funders};
749    /// let funders: Funders = WorksQuery::default().into_combined("funder id");
750    /// ```
751    pub fn into_combined<W: WorksCombiner>(self, id: &str) -> W {
752        W::ident_query(self.into_ident(id))
753    }
754
755    /// Bind the query to a specific id of a primary endpoint element
756    pub fn into_ident(self, id: &str) -> WorksIdentQuery {
757        WorksIdentQuery::new(id, self)
758    }
759
760    /// wrap this query in new `WorkListQuery` that targets the `/works` route of a primary component with an id.
761    /// The query will evaluate to the same as [`WorksQuery::into_combined`]
762    ///
763    /// # Example
764    ///
765    /// Create a query that targets all `Works` of a funder with id `funder id`
766    ///
767    /// ```no_run
768    /// # use crossref_client::{WorksQuery, Funders};
769    /// let query = WorksQuery::default()
770    ///     .into_combined_query::<Funders>("funder id");
771    ///
772    /// ```
773    pub fn into_combined_query<W: WorksCombiner>(self, id: &str) -> WorkListQuery {
774        W::work_list_query(self.into_ident(id))
775    }
776}
777
778/// Used to construct a query that targets crossref `Works` elements
779///
780/// # Example
781///
782/// ```no_run
783/// use crossref_client::{Order, WorksQuery};
784///
785/// // create a new query for topcis machine+learning ordered desc
786/// let query = WorksQuery::new("machine learning").order(Order::Desc);
787/// ```
788///
789/// Each query parameter is ANDed
790#[derive(Debug, Clone, Default)]
791pub struct WorksQuery {
792    /// search by non specific query
793    pub free_form_queries: Vec<String>,
794    /// match only particular fields of metadata
795    pub field_queries: Vec<FieldQuery>,
796    /// filter to apply while querying
797    pub filter: Vec<WorksFilter>,
798    /// sort results by a certain field and
799    pub sort: Option<Sort>,
800    /// set the sort order to `asc` or `desc`
801    pub order: Option<Order>,
802    /// elements to return
803    pub elements: Vec<WorkElement>,
804    /// enable facet information in responses
805    pub facets: Vec<FacetCount>,
806    /// deep page through `/works` result sets
807    pub result_control: Option<WorkResultControl>,
808    /// request random dois
809    /// if set all other parameters are ignored
810    pub sample: Option<usize>,
811}
812
813/// Renders `elements` into a `select` value, with [`WorkElement::DOI`] in it.
814///
815/// A [`Work`](crate::Work) requires a DOI -- it is the identifier every other
816/// field hangs off, and the one thing crossref assigns rather than accepting
817/// from the depositing member -- so a page selected without it deserializes
818/// into nothing at all. Sending it regardless costs one field per work and is
819/// the difference between a narrowed response and an [`Error::Serde`] the
820/// caller cannot act on.
821///
822/// [`Error::Serde`]: crate::Error::Serde
823fn select_value(elements: &[WorkElement]) -> String {
824    let selected = elements.iter().map(WorkElement::name);
825
826    if elements.contains(&WorkElement::DOI) {
827        selected.collect::<Vec<_>>().join(",")
828    } else {
829        std::iter::once(WorkElement::DOI.name())
830            .chain(selected)
831            .collect::<Vec<_>>()
832            .join(",")
833    }
834}
835
836impl CrossrefRoute for WorksQuery {
837    fn route(&self) -> Result<String> {
838        let mut params: Vec<(Cow<'_, str>, Cow<'_, str>)> = Vec::new();
839
840        if let Some(sample) = self.sample {
841            params.push((Cow::Borrowed("sample"), Cow::Owned(sample.to_string())));
842            return Ok(format!(
843                "{}{}",
844                Component::Works.route()?,
845                encode::query_string(&params)
846            ));
847        }
848
849        if !self.free_form_queries.is_empty() {
850            params.push((
851                Cow::Borrowed("query"),
852                Cow::Owned(format_queries(&self.free_form_queries)),
853            ));
854        }
855        params.extend(
856            self.field_queries
857                .iter()
858                .flat_map(CrossrefQueryParam::params),
859        );
860        if !self.filter.is_empty() {
861            reject_unsendable_filters(&self.filter)?;
862            params.extend(self.filter.params());
863        }
864        if !self.elements.is_empty() {
865            params.push((
866                Cow::Borrowed("select"),
867                Cow::Owned(select_value(&self.elements)),
868            ));
869        }
870        if !self.facets.is_empty() {
871            params.extend(self.facets.params());
872        }
873        if let Some(sort) = &self.sort {
874            params.extend(sort.params());
875        }
876        if let Some(order) = &self.order {
877            params.extend(order.params());
878        }
879        if let Some(rc) = &self.result_control {
880            params.extend(rc.params());
881        }
882
883        Ok(format!(
884            "{}{}",
885            Component::Works.route()?,
886            encode::query_string(&params)
887        ))
888    }
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    #[test]
896    fn serialize_works_ident() {
897        let works = Works::doi("10.1037/0003-066X.59.1.29");
898
899        assert_eq!("/works/10.1037/0003-066X.59.1.29", &works.route().unwrap())
900    }
901
902    #[test]
903    fn sample_query_keeps_the_works_route() {
904        // a bare `sample=n` used to be returned without the `/works?` prefix,
905        // which concatenated straight onto the base url
906        let route = WorksQuery::random(10).route().unwrap();
907
908        assert_eq!("/works?sample=10", &route);
909
910        let query: WorkListQuery = WorksQuery::random(10).into();
911        assert_eq!(
912            "https://api.crossref.org/works?sample=10",
913            &query.to_url("https://api.crossref.org").unwrap()
914        );
915    }
916
917    #[test]
918    fn filter_names_have_no_stray_whitespace() {
919        let route = WorksQuery::empty()
920            .filter(WorksFilter::HasClinicalTrialNumber)
921            .route()
922            .unwrap();
923
924        assert_eq!("/works?filter=has-clinical-trial-number:true", &route);
925    }
926
927    #[test]
928    fn cursor_with_rows_renders_two_parameters() {
929        let query = WorksQuery::empty().result_control(WorkResultControl::Cursor {
930            token: Some("abc".to_string()),
931            rows: Some(20),
932        });
933
934        assert_eq!("/works?cursor=abc&rows=20", &query.route().unwrap());
935    }
936
937    #[test]
938    fn new_cursor_renders_the_wildcard_token() {
939        let query = WorksQuery::empty().new_cursor();
940
941        assert_eq!("/works?cursor=*", &query.route().unwrap());
942    }
943
944    #[test]
945    fn a_query_term_can_no_longer_inject_a_parameter() {
946        // `/works?query=R&D` reaches crossref as `query=R` plus a stray `D`
947        assert_eq!(
948            "/works?query=R%26D",
949            &WorksQuery::new("R&D").route().unwrap()
950        );
951    }
952
953    #[test]
954    fn filter_and_field_query_values_are_encoded_too() {
955        let route = WorksQuery::empty()
956            .field_query(FieldQuery::container_title("Ecology & Evolution"))
957            .filter(WorksFilter::ContainerTitle("Q&A".to_string()))
958            .route()
959            .unwrap();
960
961        assert_eq!(
962            "/works?query.container-title=Ecology%20%26%20Evolution&filter=container-title:Q%26A",
963            &route
964        );
965    }
966
967    #[test]
968    fn an_empty_query_targets_the_bare_works_route() {
969        assert_eq!("/works", &WorksQuery::empty().route().unwrap());
970    }
971
972    #[test]
973    fn selected_elements_render_as_one_comma_separated_parameter() {
974        let route = WorksQuery::empty()
975            .elements(vec![WorkElement::DOI, WorkElement::Title])
976            .route()
977            .unwrap();
978
979        assert_eq!("/works?select=DOI,title", &route);
980    }
981
982    #[test]
983    fn a_select_that_omits_the_doi_still_asks_for_it() {
984        // `Work` requires a DOI, so `select=title` would come back as a page of
985        // works none of which deserialize
986        let route = WorksQuery::empty()
987            .elements(vec![WorkElement::Title])
988            .route()
989            .unwrap();
990
991        assert_eq!("/works?select=DOI,title", &route);
992    }
993
994    #[test]
995    fn a_filter_value_with_a_comma_in_it_is_refused() {
996        // crossref splits the `filter` value on `,` after decoding it, so this
997        // would arrive as `container-title:A` plus a filter called ` B`
998        let error = WorksQuery::empty()
999            .filter(WorksFilter::ContainerTitle("A, B".to_string()))
1000            .route()
1001            .expect_err("crossref cannot read this back");
1002
1003        let crate::Error::UnsendableFilterValue { filter, value } = error else {
1004            panic!("expected an unsendable filter value, got {error:?}");
1005        };
1006        assert_eq!("container-title", filter);
1007        assert_eq!("A, B", value);
1008    }
1009
1010    #[test]
1011    fn rows_offset_renders_two_parameters() {
1012        let query = WorksQuery::empty().result_control(WorkResultControl::Standard(
1013            ResultControl::RowsOffset {
1014                rows: 10,
1015                offset: 20,
1016            },
1017        ));
1018
1019        assert_eq!("/works?rows=10&offset=20", &query.route().unwrap());
1020    }
1021
1022    #[test]
1023    fn referenced_by_count_uses_the_crossref_spelling() {
1024        // `is-reference-by-count` is rejected by the api with a 400
1025        assert_eq!("is-referenced-by-count", Sort::IsReferencedByCount.as_str());
1026    }
1027}