Skip to main content

crossref_client/query/
mod.rs

1use crate::error::Result;
2pub use crate::query::funders::{Funders, FundersQuery};
3pub use crate::query::journals::{Journals, JournalsQuery};
4pub use crate::query::licenses::{Licenses, LicensesQuery};
5pub use crate::query::members::{Members, MembersQuery};
6pub use crate::query::prefixes::Prefixes;
7pub use crate::query::types::{Type, Types};
8use crate::query::works::Works;
9pub use crate::query::works::{WorksIdentQuery, WorksQuery};
10use core::fmt::Debug;
11use serde::{Deserialize, Serialize};
12use std::borrow::Cow;
13use std::fmt;
14use std::str::FromStr;
15
16/// How a filter's payload renders inside a `filter` fragment.
17///
18/// Implemented for the handful of types a filter can carry, so
19/// [`define_filter!`] can render every variant without a per-type match arm --
20/// the catch-all arm that used to do that job silently turned
21/// `WorksFilter::AlternativeId(id)` into `alternative-id:true`.
22pub(crate) trait FilterValue {
23    /// the value as it appears after the `:`
24    fn render(&self) -> Cow<'_, str>;
25}
26
27impl FilterValue for String {
28    fn render(&self) -> Cow<'_, str> {
29        Cow::Borrowed(self)
30    }
31}
32
33impl FilterValue for i32 {
34    fn render(&self) -> Cow<'_, str> {
35        Cow::Owned(self.to_string())
36    }
37}
38
39impl FilterValue for u64 {
40    fn render(&self) -> Cow<'_, str> {
41        Cow::Owned(self.to_string())
42    }
43}
44
45impl FilterValue for chrono::NaiveDate {
46    fn render(&self) -> Cow<'_, str> {
47        Cow::Owned(self.format("%Y-%m-%d").to_string())
48    }
49}
50
51impl FilterValue for types::Type {
52    fn render(&self) -> Cow<'_, str> {
53        Cow::Borrowed(self.id())
54    }
55}
56
57/// Defines a route's filter enum together with everything that has to stay in
58/// step with it: the key each variant renders under, how its payload renders,
59/// and -- for the coverage tests -- one value of every variant.
60///
61/// Marker filters carry no payload and render as `key:true`; value filters
62/// carry one, whose type implements [`FilterValue`].
63macro_rules! define_filter {
64    (
65        $(#[$meta:meta])*
66        $name:ident;
67        markers { $($(#[$m_doc:meta])* $m_variant:ident => $m_key:literal,)* }
68        values  { $($(#[$v_doc:meta])* $v_variant:ident($v_ty:ty) => $v_key:literal,)* }
69    ) => {
70        $(#[$meta])*
71        #[derive(Debug, Clone, PartialEq, Eq)]
72        pub enum $name {
73            $($(#[$m_doc])* $m_variant,)*
74            $($(#[$v_doc])* $v_variant($v_ty),)*
75        }
76
77        impl $name {
78            /// Every filter name this route accepts, in declaration order.
79            ///
80            /// Pinned against the list crossref reports in its `400` body by
81            /// the coverage tests, so it is the vocabulary of the live api
82            /// rather than of this crate's enum.
83            pub const ALL_NAMES: &'static [&'static str] = &[$($m_key,)* $($v_key,)*];
84
85            /// the key this filter renders under in the query string
86            pub fn name(&self) -> &'static str {
87                match self {
88                    $($name::$m_variant => $m_key,)*
89                    $($name::$v_variant(_) => $v_key,)*
90                }
91            }
92        }
93
94        impl $crate::query::ParamFragment for $name {
95            fn key(&self) -> ::std::borrow::Cow<'_, str> {
96                ::std::borrow::Cow::Borrowed(self.name())
97            }
98
99            fn value(&self) -> Option<::std::borrow::Cow<'_, str>> {
100                match self {
101                    $($name::$m_variant => Some(::std::borrow::Cow::Borrowed("true")),)*
102                    $($name::$v_variant(value) => {
103                        Some($crate::query::FilterValue::render(value))
104                    })*
105                }
106            }
107        }
108
109        impl $crate::query::Filter for $name {}
110    };
111}
112
113/// Defines a query for a list route that takes free form terms, paging, and
114/// optionally a filter -- and nothing else.
115///
116/// `/works` is the only route with `sort`, `order`, `facet`, `select` and
117/// `sample`; `/funders`, `/members`, `/journals` and `/licenses` all answer
118/// those with a `400`, and only the first two take a `filter` on top of terms
119/// and paging.
120macro_rules! impl_list_query {
121    ($(#[$meta:meta])* $name:ident $(, filter = $filter:ident)?) => {
122        $(#[$meta])*
123        #[derive(Debug, Clone, Default, PartialEq, Eq)]
124        pub struct $name {
125            /// search by non specific query
126            pub queries: Vec<String>,
127            $(
128                /// filter to apply while querying
129                pub filter: Vec<$filter>,
130            )?
131            /// limit the returned items and set an offset
132            ///
133            /// Only `rows` and `offset` are supported by this route;
134            /// [`ResultControl::Sample`] is rejected by crossref with a `400`.
135            pub result_control: Option<ResultControl>,
136        }
137
138        impl $name {
139            $(
140                /// add a new filter to the query
141                pub fn filter(mut self, filter: $filter) -> Self {
142                    self.filter.push(filter);
143                    self
144                }
145            )?
146            /// alias for creating an empty default element
147            pub fn empty() -> Self {
148                Self::default()
149            }
150
151            /// Convenience method to create a new query with a term directly
152            pub fn new<T: ToString>(query: T) -> Self {
153                Self::empty().query(query)
154            }
155
156            /// add a new free form query
157            pub fn query<T: ToString>(mut self, query: T) -> Self {
158                self.queries.push(query.to_string());
159                self
160            }
161
162            /// add a bunch of free form query terms
163            pub fn queries<T: ToString>(mut self, queries: &[T]) -> Self {
164                self.queries.extend(queries.iter().map(T::to_string));
165                self
166            }
167
168            /// Limit the results, or take crossref's default page if given [`None`].
169            pub fn result_control(
170                mut self,
171                result_control: impl Into<Option<ResultControl>>,
172            ) -> Self {
173                self.result_control = result_control.into();
174                self
175            }
176        }
177
178        impl CrossrefRoute for $name {
179            fn route(&self) -> Result<String> {
180                let mut params: Vec<(Cow<'_, str>, Cow<'_, str>)> = Vec::new();
181                if !self.queries.is_empty() {
182                    params.push((
183                        Cow::Borrowed("query"),
184                        Cow::Owned(format_queries(&self.queries)),
185                    ));
186                }
187                $(
188                    let filters: &[$filter] = &self.filter;
189                    if !filters.is_empty() {
190                        $crate::query::reject_unsendable_filters(filters)?;
191                        params.extend(self.filter.params());
192                    }
193                )?
194                if let Some(rc) = &self.result_control {
195                    params.extend(rc.params());
196                }
197                Ok(encode::query_string(&params))
198            }
199        }
200    };
201}
202
203/// Defines an enum of crossref identifiers together with the list of them, so
204/// a coverage test can check the list against what the api reports.
205macro_rules! define_keyed_enum {
206    (
207        $(#[$meta:meta])*
208        $name:ident { $($(#[$doc:meta])* $variant:ident => $key:literal,)* }
209    ) => {
210        $(#[$meta])*
211        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
212        pub enum $name {
213            $(
214                #[doc = concat!("the `", $key, "` field")]
215                $(#[$doc])*
216                $variant,
217            )*
218        }
219
220        impl $name {
221            /// the identifier crossref knows this by
222            pub fn name(&self) -> &'static str {
223                match self { $($name::$variant => $key,)* }
224            }
225
226            /// Every variant, in declaration order.
227            pub const ALL: &'static [$name] = &[$($name::$variant,)*];
228        }
229    };
230}
231
232/// Defines [`FieldQuery`](works::FieldQuery), the queries that match against
233/// one field of a work's metadata rather than all of it.
234///
235/// Each entry names the variant, the field crossref knows it by, and the
236/// lower-case constructor that saves callers an `into`.
237macro_rules! define_field_queries {
238    ($($(#[$doc:meta])* $variant:ident => $key:literal / $ctor:ident,)*) => {
239        /// Matches against one field of a work's metadata rather than all of
240        /// it. Available on the `/works` route only.
241        ///
242        /// ```
243        /// # use crossref_client::FieldQuery;
244        /// assert_eq!("query.author", FieldQuery::author("feynman").name());
245        /// ```
246        ///
247        /// Covers all 21 field queries `/works` accepts, which
248        /// `every_field_query_is_accepted_by_the_api` pins against what the api
249        /// reports.
250        #[derive(Debug, Clone, PartialEq, Eq)]
251        pub enum FieldQuery {
252            $(
253                #[doc = concat!("matches against `", $key, "`: ")]
254                $(#[$doc])*
255                $variant(String),
256            )*
257        }
258
259        impl FieldQuery {
260            /// Every field `/works` can be queried against, in declaration
261            /// order -- the `author` of `query.author`.
262            pub const ALL_FIELDS: &'static [&'static str] = &[$($key,)*];
263
264            /// the key this renders under in the query string, e.g. `query.author`
265            pub fn name(&self) -> &'static str {
266                match self { $(FieldQuery::$variant(_) => concat!("query.", $key),)* }
267            }
268
269            /// the field crossref knows this by, e.g. `author`
270            pub fn field(&self) -> &'static str {
271                match self { $(FieldQuery::$variant(_) => $key,)* }
272            }
273
274            /// the term being matched
275            pub fn value(&self) -> &str {
276                match self { $(FieldQuery::$variant(value) => value,)* }
277            }
278
279            $(
280                #[doc = concat!("a query against `", $key, "`")]
281                pub fn $ctor(value: impl Into<String>) -> Self {
282                    FieldQuery::$variant(value.into())
283                }
284            )*
285        }
286    };
287}
288
289/// percent-encoding of the crossref query string
290pub(crate) mod encode;
291/// provides types to filter facets
292pub mod facet;
293/// provides support to query the `/funders` route
294pub mod funders;
295/// provides support to query the `/funders` route
296pub mod journals;
297/// provides support to query the `/licenses` route
298pub mod licenses;
299/// provides support to query the `/members` route
300pub mod members;
301/// provides support to query the `/members` route
302pub mod prefixes;
303/// provides support to query the `/prefixes` route
304pub mod types;
305/// provides support to query the `/types` route
306pub mod works;
307
308/// represents the visibility of an crossref item
309#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
310#[serde(rename_all = "kebab-case")]
311pub enum Visibility {
312    /// readable by anyone
313    Open,
314    /// readable by Metadata Plus subscribers
315    Limited,
316    /// not readable
317    Closed,
318}
319
320impl Visibility {
321    /// str identifier
322    pub fn as_str(&self) -> &str {
323        match self {
324            Visibility::Open => "open",
325            Visibility::Limited => "limited",
326            Visibility::Closed => "closed",
327        }
328    }
329}
330
331/// Determines how results should be sorted
332#[derive(Debug, PartialEq, Eq, Clone, Copy)]
333pub enum Order {
334    /// list results in ascending order
335    Asc,
336    /// list results in descending order
337    Desc,
338}
339
340impl Order {
341    /// the key name for the order parameter
342    pub fn as_str(&self) -> &str {
343        match self {
344            Order::Asc => "asc",
345            Order::Desc => "desc",
346        }
347    }
348}
349
350impl FromStr for Order {
351    type Err = String;
352
353    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
354        match s {
355            "asc" => Ok(Order::Asc),
356            "desc" => Ok(Order::Desc),
357            other => Err(format!("Unable to convert {} to Order", other)),
358        }
359    }
360}
361
362impl CrossrefQueryParam for Order {
363    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
364        vec![(Cow::Borrowed("order"), Cow::Borrowed(self.as_str()))]
365    }
366}
367
368/// Results from a list response can be sorted by applying the sort and order parameters.
369#[derive(Debug, PartialEq, Eq, Clone, Copy)]
370pub enum Sort {
371    /// Sort by relevance score
372    Score,
373    /// Sort by date of most recent change to metadata. Currently the same as `Deposited`
374    Updated,
375    /// Sort by time of most recent deposit
376    Deposited,
377    /// Sort by time of most recent index
378    Indexed,
379    /// Sort by publication date
380    Published,
381    /// Sort by print publication date
382    PublishedPrint,
383    /// Sort by online publication date
384    PublishedOnline,
385    /// Sort by issued date (earliest known publication date)
386    Issued,
387    /// Sort by number of times this DOI is referenced by other Crossref DOIs
388    IsReferencedByCount,
389    /// Sort by number of references included in the references section of the document identified by this DOI
390    ReferenceCount,
391    /// Sort by date the record was created
392    Created,
393    /// Sort by relevance to the query terms
394    Relevance,
395}
396
397impl Sort {
398    /// Every field `/works` can be sorted by, in declaration order.
399    pub const ALL: &'static [Sort] = &[
400        Sort::Score,
401        Sort::Updated,
402        Sort::Deposited,
403        Sort::Indexed,
404        Sort::Published,
405        Sort::PublishedPrint,
406        Sort::PublishedOnline,
407        Sort::Issued,
408        Sort::IsReferencedByCount,
409        Sort::ReferenceCount,
410        Sort::Created,
411        Sort::Relevance,
412    ];
413
414    /// the key name for the filter element
415    pub fn as_str(&self) -> &str {
416        match self {
417            Sort::Score => "score",
418            Sort::Updated => "updated",
419            Sort::Deposited => "deposited",
420            Sort::Indexed => "indexed",
421            Sort::Published => "published",
422            Sort::PublishedPrint => "published-print",
423            Sort::PublishedOnline => "published-online",
424            Sort::Issued => "issued",
425            Sort::IsReferencedByCount => "is-referenced-by-count",
426            Sort::ReferenceCount => "references-count",
427            Sort::Created => "created",
428            Sort::Relevance => "relevance",
429        }
430    }
431}
432
433impl FromStr for Sort {
434    type Err = String;
435
436    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
437        match s {
438            "score" => Ok(Sort::Score),
439            "updated" => Ok(Sort::Updated),
440            "deposited" => Ok(Sort::Deposited),
441            "indexed" => Ok(Sort::Indexed),
442            "published" => Ok(Sort::Published),
443            "published-print" => Ok(Sort::PublishedPrint),
444            "published-online" => Ok(Sort::PublishedOnline),
445            "issued" => Ok(Sort::Issued),
446            "is-referenced-by-count" => Ok(Sort::IsReferencedByCount),
447            "references-count" => Ok(Sort::ReferenceCount),
448            "created" => Ok(Sort::Created),
449            "relevance" => Ok(Sort::Relevance),
450            other => Err(format!("Unable to convert {} to Sort", other)),
451        }
452    }
453}
454
455impl CrossrefQueryParam for Sort {
456    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
457        vec![(Cow::Borrowed("sort"), Cow::Borrowed(self.as_str()))]
458    }
459}
460
461/// tells crossref how many items shall be returned or where to start
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub enum ResultControl {
464    /// limits the returned items per page
465    Rows(usize),
466    /// sets an offset where crossref begins to retrieve items
467    /// high offsets (~10k) result in long response times
468    Offset(usize),
469    /// combines rows and offset: limit returned items per page, starting at the offset
470    RowsOffset {
471        /// row limit
472        rows: usize,
473        /// where to start
474        offset: usize,
475    },
476    /// return random results
477    Sample(usize),
478}
479
480impl CrossrefQueryParam for ResultControl {
481    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
482        match self {
483            ResultControl::Rows(rows) => {
484                vec![(Cow::Borrowed("rows"), Cow::Owned(rows.to_string()))]
485            }
486            ResultControl::Offset(offset) => {
487                vec![(Cow::Borrowed("offset"), Cow::Owned(offset.to_string()))]
488            }
489            ResultControl::RowsOffset { rows, offset } => vec![
490                (Cow::Borrowed("rows"), Cow::Owned(rows.to_string())),
491                (Cow::Borrowed("offset"), Cow::Owned(offset.to_string())),
492            ],
493            ResultControl::Sample(sample) => {
494                vec![(Cow::Borrowed("sample"), Cow::Owned(sample.to_string()))]
495            }
496        }
497    }
498}
499
500/// Major resource components supported by the Crossref API
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
502#[serde(rename_all = "lowercase")]
503pub enum Component {
504    /// a list of all works (journal articles, conference proceedings, books, components, etc), 20 per page
505    Works,
506    /// a list of all funders in the [Funder Registry](https://github.com/Crossref/open-funder-registry)
507    Funders,
508    /// a list of DOI owner prefixes
509    Prefixes,
510    /// a list of all Crossref members (mostly publishers)
511    Members,
512    /// a list of valid work types
513    Types,
514    /// a list of journals in the Crossref database
515    Journals,
516    /// a list of the licenses works in the Crossref metadata are published under
517    Licenses,
518}
519
520impl Component {
521    /// identifier for the component route
522    pub fn as_str(&self) -> &str {
523        match self {
524            Component::Works => "works",
525            Component::Funders => "funders",
526            Component::Prefixes => "prefixes",
527            Component::Members => "members",
528            Component::Types => "types",
529            Component::Journals => "journals",
530            Component::Licenses => "licenses",
531        }
532    }
533}
534
535impl CrossrefRoute for Component {
536    fn route(&self) -> Result<String> {
537        Ok(format!("/{}", self.as_str()))
538    }
539}
540
541/// The components that also expose their works at `/{component}/{id}/works`.
542///
543/// A narrower [`Component`]: `/works` has no such sub-route of its own, and
544/// neither does `/licenses`.
545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
546pub enum WorksComponent {
547    /// works of one funder, at `/funders/{id}/works`
548    Funders,
549    /// works of one DOI prefix, at `/prefixes/{id}/works`
550    Prefixes,
551    /// works of one member, at `/members/{id}/works`
552    Members,
553    /// works of one type, at `/types/{id}/works`
554    Types,
555    /// works of one journal, at `/journals/{issn}/works`
556    Journals,
557}
558
559impl WorksComponent {
560    /// the route this component owns
561    pub fn component(&self) -> Component {
562        match self {
563            WorksComponent::Funders => Component::Funders,
564            WorksComponent::Prefixes => Component::Prefixes,
565            WorksComponent::Members => Component::Members,
566            WorksComponent::Types => Component::Types,
567            WorksComponent::Journals => Component::Journals,
568        }
569    }
570}
571
572impl CrossrefRoute for WorksComponent {
573    fn route(&self) -> Result<String> {
574        self.component().route()
575    }
576}
577
578/// bundles all available crossref api endpoints
579#[derive(Debug, Clone)]
580pub enum ResourceComponent {
581    /// the `/works` route
582    Works(Works),
583    /// the `/funders` route
584    Funders(Funders),
585    /// the `/prefixes` route
586    Prefixes(Prefixes),
587    /// the `/members` route
588    Members(Members),
589    /// the `/types` route
590    Types(Types),
591    /// the `/journals` route
592    Journals(Journals),
593    /// the `/licenses` route
594    Licenses(Licenses),
595}
596
597impl ResourceComponent {
598    /// the starting crossref component that in the route `/{primary_component}/{id}/works`
599    pub fn primary_component(&self) -> Component {
600        match self {
601            ResourceComponent::Works(_) => Component::Works,
602            ResourceComponent::Funders(_) => Component::Funders,
603            ResourceComponent::Prefixes(_) => Component::Prefixes,
604            ResourceComponent::Members(_) => Component::Members,
605            ResourceComponent::Types(_) => Component::Types,
606            ResourceComponent::Journals(_) => Component::Journals,
607            ResourceComponent::Licenses(_) => Component::Licenses,
608        }
609    }
610}
611
612impl fmt::Display for ResourceComponent {
613    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614        write!(f, "{}", self.route().map_err(|_| fmt::Error)?)
615    }
616}
617
618impl CrossrefRoute for ResourceComponent {
619    fn route(&self) -> Result<String> {
620        match self {
621            ResourceComponent::Works(c) => c.route(),
622            ResourceComponent::Funders(c) => c.route(),
623            ResourceComponent::Prefixes(c) => c.route(),
624            ResourceComponent::Members(c) => c.route(),
625            ResourceComponent::Types(c) => c.route(),
626            ResourceComponent::Journals(c) => c.route(),
627            ResourceComponent::Licenses(c) => c.route(),
628        }
629    }
630}
631
632impl CrossrefQuery for ResourceComponent {
633    fn resource_component(self) -> ResourceComponent {
634        self
635    }
636}
637
638/// Helper trait to mark filters in the query string
639pub trait Filter: ParamFragment {}
640
641impl<T: Filter> CrossrefQueryParam for Vec<T> {
642    /// filters share the `filter` key and are concat with `,`
643    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
644        vec![(
645            Cow::Borrowed("filter"),
646            Cow::Owned(
647                self.iter()
648                    .map(ParamFragment::fragment)
649                    .collect::<Vec<_>>()
650                    .join(","),
651            ),
652        )]
653    }
654}
655
656/// represents a key value pair inside a multi value query string parameter
657pub trait ParamFragment {
658    /// the key, or name, of the fragment
659    fn key(&self) -> Cow<'_, str>;
660
661    /// the value of the fragment, if any
662    fn value(&self) -> Option<Cow<'_, str>>;
663
664    /// key and value are concat using `:`
665    fn fragment(&self) -> Cow<'_, str> {
666        if let Some(val) = self.value() {
667            Cow::Owned(format!("{}:{}", self.key(), val))
668        } else {
669            self.key()
670        }
671    }
672}
673
674/// a trait used to capture parameters for the query string of the crossref api
675pub trait CrossrefQueryParam {
676    /// The key/value pairs this element contributes to the query string.
677    ///
678    /// Most elements contribute exactly one pair, but a few span two --
679    /// [`ResultControl::RowsOffset`] and [`works::WorkResultControl::Cursor`]
680    /// with a row limit. Yielding pairs rather than a rendered `key=value`
681    /// fragment is what lets the route builder percent-encode keys and values
682    /// separately.
683    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)>;
684}
685
686impl<T: AsRef<str>> CrossrefQueryParam for (T, T) {
687    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
688        vec![(
689            Cow::Borrowed(self.0.as_ref()),
690            Cow::Borrowed(self.1.as_ref()),
691        )]
692    }
693}
694
695/// represents elements that constructs parts of the crossref request url
696pub trait CrossrefRoute {
697    /// constructs the route for the crossref api
698    fn route(&self) -> Result<String>;
699}
700
701/// root level trait to construct full crossref api request urls
702pub trait CrossrefQuery: CrossrefRoute + Clone {
703    /// the resource component endpoint this route targets
704    fn resource_component(self) -> ResourceComponent;
705
706    /// constructs the full request url by concating the `base_path` with the `route`
707    fn to_url(&self, base_path: &str) -> Result<String> {
708        Ok(format!("{}{}", base_path, self.route()?))
709    }
710}
711
712/// Refuses a filter value crossref would read as two filters.
713///
714/// Crossref splits the `filter` value on `,` *after* percent-decoding it, so a
715/// value carrying one arrives as two fragments -- `container-title:A, B`
716/// becomes the filter `container-title:A` plus a filter called ` B`, which the
717/// api answers with a `400`. Neither the encoded nor the literal form survives,
718/// so there is nothing to escape it with and the request is refused here
719/// instead, where the error can say which filter is at fault.
720pub(crate) fn reject_unsendable_filters<T: Filter>(filters: &[T]) -> Result<()> {
721    for filter in filters {
722        match filter.value() {
723            Some(value) if value.contains(',') => {
724                return Err(crate::Error::UnsendableFilterValue {
725                    filter: filter.key().into_owned(),
726                    value: value.into_owned(),
727                });
728            }
729            _ => (),
730        }
731    }
732    Ok(())
733}
734
735/// normalizes a query term by collapsing runs of whitespace into single spaces
736///
737/// Crossref reads the `query` value as a whitespace separated list of terms.
738/// The separator is a plain space rather than the `+` it renders as on the wire,
739/// because [`encode`] escapes the value afterwards and a literal `+` there would
740/// come back out as one.
741pub(crate) fn format_query<T: AsRef<str>>(topic: T) -> String {
742    topic
743        .as_ref()
744        .split_whitespace()
745        .collect::<Vec<_>>()
746        .join(" ")
747}
748
749/// combines the individual topics of a query into a single `query` value
750pub(crate) fn format_queries<T: AsRef<str>>(topics: &[T]) -> String {
751    topics
752        .iter()
753        .flat_map(|topic| topic.as_ref().split_whitespace())
754        .collect::<Vec<_>>()
755        .join(" ")
756}
757
758/// Pins this crate's idea of a route's vocabulary against crossref's.
759///
760/// Crossref answers an unrecognised filter, sort field, field query or `select`
761/// element with a `400` that lists the ones it does know, so the lists below
762/// are copied from those responses. Checking both directions catches a name
763/// this crate would send and crossref would reject, *and* one crossref accepts
764/// that this crate cannot express.
765#[cfg(test)]
766fn assert_matches_api(kind: &str, ours: &[&str], api: &[&str]) {
767    use std::collections::BTreeSet;
768
769    let mine: BTreeSet<&str> = ours.iter().copied().collect();
770    assert_eq!(ours.len(), mine.len(), "duplicate {kind} in this crate");
771
772    let theirs: BTreeSet<&str> = api.iter().copied().collect();
773    assert_eq!(api.len(), theirs.len(), "duplicate {kind} in the api list");
774
775    let rejected: Vec<_> = mine.difference(&theirs).collect();
776    assert!(
777        rejected.is_empty(),
778        "{kind} this crate sends that crossref answers with a 400: {rejected:?}"
779    );
780
781    let unreachable: Vec<_> = theirs.difference(&mine).collect();
782    assert!(
783        unreachable.is_empty(),
784        "{kind} crossref accepts that this crate cannot express: {unreachable:?}"
785    );
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791    use crate::query::funders::FundersFilter;
792    use crate::query::members::MembersFilter;
793    use crate::query::works::{FieldQuery, WorkElement, WorksFilter};
794
795    /// The set crossref reports in its `400` response for an unknown sort field.
796    const API_SORT_FIELDS: &[&str] = &[
797        "score",
798        "created",
799        "issued",
800        "indexed",
801        "is-referenced-by-count",
802        "relevance",
803        "published",
804        "published-print",
805        "published-online",
806        "updated",
807        "references-count",
808        "deposited",
809    ];
810
811    #[test]
812    fn every_sort_key_is_accepted_by_the_api() {
813        let names: Vec<&str> = Sort::ALL.iter().map(Sort::as_str).collect();
814
815        assert_matches_api("/works sort fields", &names, API_SORT_FIELDS);
816    }
817
818    #[test]
819    fn sort_round_trips_through_from_str() {
820        for sort in Sort::ALL {
821            assert_eq!(Ok(*sort), Sort::from_str(sort.as_str()));
822        }
823    }
824
825    #[test]
826    fn order_round_trips_through_from_str() {
827        for order in [Order::Asc, Order::Desc] {
828            assert_eq!(Ok(order), Order::from_str(order.as_str()));
829        }
830    }
831
832    /// The filters crossref reports for `/works`.
833    const API_WORKS_FILTERS: &[&str] = &[
834        "alternative-id",
835        "archive",
836        "article-number",
837        "assertion",
838        "assertion-group",
839        "award.funder",
840        "award.number",
841        "category-name",
842        "clinical-trial-number",
843        "container-title",
844        "content-domain",
845        "directory",
846        "doi",
847        "from-accepted-date",
848        "from-approved-date",
849        "from-awarded-date",
850        "from-created-date",
851        "from-deposit-date",
852        "from-event-end-date",
853        "from-event-start-date",
854        "from-index-date",
855        "from-issued-date",
856        "from-online-pub-date",
857        "from-posted-date",
858        "from-print-pub-date",
859        "from-pub-date",
860        "from-update-date",
861        "full-text.application",
862        "full-text.type",
863        "full-text.version",
864        "funder",
865        "funder-doi-asserted-by",
866        "group-title",
867        "gte-award-amount",
868        "has-abstract",
869        "has-affiliation",
870        "has-affiliation-ror-id",
871        "has-alias",
872        "has-archive",
873        "has-assertion",
874        "has-authenticated-orcid",
875        "has-award",
876        "has-clinical-trial-number",
877        "has-content-domain",
878        "has-domain-restriction",
879        "has-event",
880        "has-full-text",
881        "has-funder",
882        "has-funder-doi",
883        "has-funder-ror-id",
884        "has-license",
885        "has-orcid",
886        "has-prime-doi",
887        "has-references",
888        "has-relation",
889        "has-ror-id",
890        "has-update",
891        "has-update-policy",
892        "is-update",
893        "isbn",
894        "issn",
895        "license.delay",
896        "license.url",
897        "license.version",
898        "lte-award-amount",
899        "member",
900        "orcid",
901        "prefix",
902        "relation.object",
903        "relation.object-type",
904        "relation.type",
905        "ror-id",
906        "type",
907        "type-name",
908        "until-accepted-date",
909        "until-approved-date",
910        "until-awarded-date",
911        "until-created-date",
912        "until-deposit-date",
913        "until-event-end-date",
914        "until-event-start-date",
915        "until-index-date",
916        "until-issued-date",
917        "until-online-pub-date",
918        "until-posted-date",
919        "until-print-pub-date",
920        "until-pub-date",
921        "until-update-date",
922        "update-type",
923        "updates",
924    ];
925
926    /// The field queries crossref reports for `/works`.
927    const API_FIELD_QUERIES: &[&str] = &[
928        "affiliation",
929        "author",
930        "bibliographic",
931        "chair",
932        "container-title",
933        "contributor",
934        "degree",
935        "description",
936        "editor",
937        "event-acronym",
938        "event-location",
939        "event-name",
940        "event-sponsor",
941        "event-theme",
942        "funder-name",
943        "publisher-location",
944        "publisher-name",
945        "standards-body-acronym",
946        "standards-body-name",
947        "title",
948        "translator",
949    ];
950
951    /// The `select` elements crossref reports for `/works`.
952    const API_WORK_ELEMENTS: &[&str] = &[
953        "DOI",
954        "ISBN",
955        "ISSN",
956        "URL",
957        "abstract",
958        "accepted",
959        "alternative-id",
960        "approved",
961        "archive",
962        "article-number",
963        "assertion",
964        "author",
965        "chair",
966        "clinical-trial-number",
967        "container-title",
968        "content-created",
969        "content-domain",
970        "contributor",
971        "created",
972        "degree",
973        "deposited",
974        "editor",
975        "event",
976        "funder",
977        "group-title",
978        "indexed",
979        "is-referenced-by-count",
980        "issn-type",
981        "issue",
982        "issued",
983        "license",
984        "link",
985        "member",
986        "original-title",
987        "page",
988        "posted",
989        "prefix",
990        "published",
991        "published-online",
992        "published-print",
993        "publisher",
994        "publisher-location",
995        "reference",
996        "references-count",
997        "relation",
998        "resource",
999        "score",
1000        "short-container-title",
1001        "short-title",
1002        "standards-body",
1003        "subject",
1004        "subtitle",
1005        "title",
1006        "translator",
1007        "type",
1008        "update-policy",
1009        "update-to",
1010        "updated-by",
1011        "volume",
1012    ];
1013
1014    /// The filters crossref reports for `/funders`.
1015    const API_FUNDERS_FILTERS: &[&str] = &["location"];
1016
1017    /// The filters crossref reports for `/members`.
1018    const API_MEMBERS_FILTERS: &[&str] = &["prefix", "backfile-doi-count", "current-doi-count"];
1019
1020    #[test]
1021    fn every_works_filter_is_accepted_by_the_api() {
1022        assert_matches_api("/works filters", WorksFilter::ALL_NAMES, API_WORKS_FILTERS);
1023    }
1024
1025    #[test]
1026    fn every_field_query_is_accepted_by_the_api() {
1027        assert_matches_api(
1028            "/works field queries",
1029            FieldQuery::ALL_FIELDS,
1030            API_FIELD_QUERIES,
1031        );
1032    }
1033
1034    #[test]
1035    fn every_selectable_element_is_accepted_by_the_api() {
1036        let names: Vec<&str> = WorkElement::ALL.iter().map(WorkElement::name).collect();
1037
1038        assert_matches_api("/works select elements", &names, API_WORK_ELEMENTS);
1039    }
1040
1041    #[test]
1042    fn every_funders_filter_is_accepted_by_the_api() {
1043        assert_matches_api(
1044            "/funders filters",
1045            FundersFilter::ALL_NAMES,
1046            API_FUNDERS_FILTERS,
1047        );
1048    }
1049
1050    #[test]
1051    fn every_members_filter_is_accepted_by_the_api() {
1052        assert_matches_api(
1053            "/members filters",
1054            MembersFilter::ALL_NAMES,
1055            API_MEMBERS_FILTERS,
1056        );
1057    }
1058
1059    #[test]
1060    fn a_marker_filter_renders_as_true_and_a_value_filter_as_its_value() {
1061        let filters = vec![
1062            WorksFilter::HasOrcid,
1063            WorksFilter::AlternativeId("abc".to_string()),
1064            WorksFilter::LicenseDelay(30),
1065            WorksFilter::GteAwardAmount(1_000),
1066        ];
1067
1068        assert_eq!(
1069            vec![(
1070                Cow::Borrowed("filter"),
1071                Cow::Owned(
1072                    "has-orcid:true,alternative-id:abc,license.delay:30,gte-award-amount:1000"
1073                        .to_string()
1074                )
1075            )],
1076            filters.params()
1077        );
1078    }
1079}