Skip to main content

crossref/query/
mod.rs

1use crate::error::Result;
2use crate::query::facet::FacetCount;
3pub use crate::query::funders::{Funders, FundersQuery};
4pub use crate::query::journals::Journals;
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 serde::{Deserialize, Serialize};
11use std::borrow::Cow;
12use std::fmt;
13#[cfg(feature = "cli")]
14use std::str::FromStr;
15#[cfg(feature = "cli")]
16use structopt::StructOpt;
17
18/// Helper trait for unified interface
19pub trait CrossrefParams {
20    /// the filter applied
21    type Filter: Filter;
22    /// all string queries
23    fn query_terms(&self) -> &[String];
24    /// the filters this object can use
25    fn filters(&self) -> &[Self::Filter];
26    /// the sort if set
27    fn sort(&self) -> Option<&Sort>;
28    /// the order if set
29    fn order(&self) -> Option<&Order>;
30    /// all facets this objects addresses
31    fn facets(&self) -> &[FacetCount];
32    /// the configured result control, if any
33    fn result_control(&self) -> Option<&ResultControl>;
34}
35
36macro_rules! impl_common_query {
37    ($i:ident, $filter:ident) => {
38        /// Each query parameter is ANDed
39        #[derive(Debug, Clone, Default)]
40        pub struct $i {
41            /// search by non specific query
42            pub queries: Vec<String>,
43            /// filter to apply while querying
44            pub filter: Vec<$filter>,
45            /// sort results by a certain field and
46            pub sort: Option<Sort>,
47            /// set the sort order to `asc` or `desc`
48            pub order: Option<Order>,
49            /// enable facet information in responses
50            pub facets: Vec<FacetCount>,
51            /// deep page through `/works` result sets
52            pub result_control: Option<ResultControl>,
53        }
54
55        impl $i {
56            /// alias for creating an empty default element
57            pub fn empty() -> Self {
58                $i::default()
59            }
60
61            /// Convenience method to create a new query with a term directly
62            pub fn new<T: ToString>(query: T) -> Self {
63                Self::empty().query(query)
64            }
65
66            /// add a new free form query
67            pub fn query<T: ToString>(mut self, query: T) -> Self {
68                self.queries.push(query.to_string());
69                self
70            }
71
72            /// add a new filter to the query
73            pub fn filter(mut self, filter: $filter) -> Self {
74                self.filter.push(filter);
75                self
76            }
77
78            /// set sort option to the query
79            pub fn sort(mut self, sort: Sort) -> Self {
80                self.sort = Some(sort);
81                self
82            }
83
84            /// set order to asc
85            pub fn order_asc(mut self) -> Self {
86                self.order = Some(Order::Asc);
87                self
88            }
89            /// set order to desc
90            pub fn order_desc(mut self) -> Self {
91                self.order = Some(Order::Desc);
92                self
93            }
94
95            /// set order option to query
96            pub fn order(mut self, order: Order) -> Self {
97                self.order = Some(order);
98                self
99            }
100
101            /// add another facet to query
102            pub fn facet(mut self, facet: FacetCount) -> Self {
103                self.facets.push(facet);
104                self
105            }
106
107            /// set result control option to query
108            pub fn result_control(mut self, result_control: ResultControl) -> Self {
109                self.result_control = Some(result_control);
110                self
111            }
112        }
113
114        impl CrossrefParams for $i {
115            type Filter = $filter;
116
117            fn query_terms(&self) -> &[String] {
118                &self.queries
119            }
120            fn filters(&self) -> &[Self::Filter] {
121                &self.filter
122            }
123            fn sort(&self) -> Option<&Sort> {
124                self.sort.as_ref()
125            }
126            fn order(&self) -> Option<&Order> {
127                self.order.as_ref()
128            }
129            fn facets(&self) -> &[FacetCount] {
130                &self.facets
131            }
132            fn result_control(&self) -> Option<&ResultControl> {
133                self.result_control.as_ref()
134            }
135        }
136
137        impl CrossrefRoute for $i {
138            fn route(&self) -> Result<String> {
139                let mut params = Vec::new();
140                if !self.queries.is_empty() {
141                    params.push(Cow::Owned(format!(
142                        "query={}",
143                        format_queries(&self.queries)
144                    )));
145                }
146                if !self.filter.is_empty() {
147                    params.push(self.filter.param());
148                }
149                if !self.facets.is_empty() {
150                    params.push(self.facets.param());
151                }
152                if let Some(sort) = &self.sort {
153                    params.push(sort.param());
154                }
155                if let Some(order) = &self.order {
156                    params.push(order.param());
157                }
158                if let Some(rc) = &self.result_control {
159                    params.push(rc.param());
160                }
161                Ok(params.join("&"))
162            }
163        }
164    };
165}
166
167/// provides types to filter facets
168pub mod facet;
169/// provides support to query the `/funders` route
170pub mod funders;
171/// provides support to query the `/funders` route
172pub mod journals;
173/// provides support to query the `/journals` route
174pub mod members;
175/// provides support to query the `/members` route
176pub mod prefixes;
177/// provides support to query the `/prefixes` route
178pub mod types;
179/// provides support to query the `/types` route
180pub mod works;
181
182/// represents the visibility of an crossref item
183#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
184#[serde(rename_all = "kebab-case")]
185#[allow(missing_docs)]
186pub enum Visibility {
187    Open,
188    Limited,
189    Closed,
190}
191
192impl Visibility {
193    /// str identifier
194    pub fn as_str(&self) -> &str {
195        match self {
196            Visibility::Open => "open",
197            Visibility::Limited => "limited",
198            Visibility::Closed => "closed",
199        }
200    }
201}
202
203/// Determines how results should be sorted
204#[derive(Debug, PartialEq, Eq, Clone)]
205#[cfg_attr(feature = "cli", derive(StructOpt))]
206pub enum Order {
207    /// list results in ascending order
208    #[cfg_attr(
209        feature = "cli",
210        structopt(name = "asc", about = "list results in ascending order")
211    )]
212    Asc,
213    /// list results in descending order
214    #[cfg_attr(
215        feature = "cli",
216        structopt(name = "desc", about = "list results in descending order")
217    )]
218    Desc,
219}
220
221impl Order {
222    /// the key name for the order parameter
223    pub fn as_str(&self) -> &str {
224        match self {
225            Order::Asc => "asc",
226            Order::Desc => "desc",
227        }
228    }
229}
230
231#[cfg(feature = "cli")]
232impl FromStr for Order {
233    type Err = String;
234
235    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
236        match s {
237            "asc" => Ok(Order::Asc),
238            "desc" => Ok(Order::Desc),
239            other => Err(format!("Unable to convert {} to Order", other)),
240        }
241    }
242}
243
244impl CrossrefQueryParam for Order {
245    fn param_key(&self) -> Cow<'_, str> {
246        Cow::Borrowed("order")
247    }
248
249    fn param_value(&self) -> Option<Cow<'_, str>> {
250        Some(Cow::Borrowed(self.as_str()))
251    }
252}
253
254/// Results from a list response can be sorted by applying the sort and order parameters.
255#[derive(Debug, Clone)]
256#[cfg_attr(feature = "cli", derive(StructOpt))]
257pub enum Sort {
258    /// Sort by relevance score
259    #[cfg_attr(
260        feature = "cli",
261        structopt(name = "score", about = "Sort by the relevance score")
262    )]
263    Score,
264    /// Sort by date of most recent change to metadata. Currently the same as `Deposited`
265    #[cfg_attr(
266        feature = "cli",
267        structopt(
268            name = "updated",
269            about = "Sort by date of most recent change to metadata."
270        )
271    )]
272    Updated,
273    /// Sort by time of most recent deposit
274    #[cfg_attr(
275        feature = "cli",
276        structopt(name = "deposited", about = "Sort by time of most recent deposit")
277    )]
278    Deposited,
279    /// Sort by time of most recent index
280    #[cfg_attr(
281        feature = "cli",
282        structopt(name = "indexed", about = "Sort by time of most recent index")
283    )]
284    Indexed,
285    /// Sort by publication date
286    #[cfg_attr(
287        feature = "cli",
288        structopt(name = "published", about = "Sort by publication date")
289    )]
290    Published,
291    /// Sort by print publication date
292    #[cfg_attr(
293        feature = "cli",
294        structopt(name = "published-print", about = "Sort by print publication date")
295    )]
296    PublishedPrint,
297    /// Sort by online publication date
298    #[cfg_attr(
299        feature = "cli",
300        structopt(name = "published-online", about = "Sort by online publication date")
301    )]
302    PublishedOnline,
303    /// Sort by issued date (earliest known publication date)
304    #[cfg_attr(
305        feature = "cli",
306        structopt(
307            name = "issued",
308            about = "Sort by issued date (earliest known publication date)"
309        )
310    )]
311    Issued,
312    /// Sort by number of times this DOI is referenced by other Crossref DOIs
313    #[cfg_attr(
314        feature = "cli",
315        structopt(
316            name = "is-referenced-by-count",
317            about = "Sort by number of times this DOI is referenced by other Crossref DOIs"
318        )
319    )]
320    IsReferencedByCount,
321    /// Sort by number of references included in the references section of the document identified by this DOI
322    #[cfg_attr(
323        feature = "cli",
324        structopt(
325            name = "reference-count",
326            about = "Sort by number of references included in the references section of the document identified by this DOI"
327        )
328    )]
329    ReferenceCount,
330}
331
332impl Sort {
333    /// the key name for the filter element
334    pub fn as_str(&self) -> &str {
335        match self {
336            Sort::Score => "score",
337            Sort::Updated => "updated",
338            Sort::Deposited => "deposited",
339            Sort::Indexed => "indexed",
340            Sort::Published => "published",
341            Sort::PublishedPrint => "published-print",
342            Sort::PublishedOnline => "published-online",
343            Sort::Issued => "issued",
344            Sort::IsReferencedByCount => "is-reference-by-count",
345            Sort::ReferenceCount => "reference-count",
346        }
347    }
348}
349
350#[cfg(feature = "cli")]
351impl FromStr for Sort {
352    type Err = String;
353
354    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
355        match s {
356            "score" => Ok(Sort::Score),
357            "updated" => Ok(Sort::Updated),
358            "deposited" => Ok(Sort::Deposited),
359            "indexed" => Ok(Sort::Indexed),
360            "published" => Ok(Sort::Published),
361            "published-print" => Ok(Sort::PublishedPrint),
362            "published-online" => Ok(Sort::PublishedOnline),
363            "issued" => Ok(Sort::Issued),
364            "is-reference-by-count" => Ok(Sort::IsReferencedByCount),
365            "reference-count" => Ok(Sort::ReferenceCount),
366            other => Err(format!("Unable to convert {} to Sort", other)),
367        }
368    }
369}
370
371impl CrossrefQueryParam for Sort {
372    fn param_key(&self) -> Cow<'_, str> {
373        Cow::Borrowed("sort")
374    }
375
376    fn param_value(&self) -> Option<Cow<'_, str>> {
377        Some(Cow::Borrowed(self.as_str()))
378    }
379}
380
381/// tells crossref how many items shall be returned or where to start
382#[derive(Debug, Clone)]
383pub enum ResultControl {
384    /// limits the returned items per page
385    Rows(usize),
386    /// sets an offset where crossref begins to retrieve items
387    /// high offsets (~10k) result in long response times
388    Offset(usize),
389    /// combines rows and offset: limit returned items per page, starting at the offset
390    RowsOffset {
391        /// row limit
392        rows: usize,
393        /// where to start
394        offset: usize,
395    },
396    /// return random results
397    Sample(usize),
398}
399
400impl CrossrefQueryParam for ResultControl {
401    fn param_key(&self) -> Cow<'_, str> {
402        match self {
403            ResultControl::Rows(_) => Cow::Borrowed("rows"),
404            ResultControl::Offset(_) => Cow::Borrowed("offset"),
405            ResultControl::RowsOffset { .. } => Cow::Borrowed("rows"),
406            ResultControl::Sample(_) => Cow::Borrowed("sample"),
407        }
408    }
409
410    fn param_value(&self) -> Option<Cow<'_, str>> {
411        match self {
412            ResultControl::Rows(r) | ResultControl::Offset(r) | ResultControl::Sample(r) => {
413                Some(Cow::Owned(r.to_string()))
414            }
415            ResultControl::RowsOffset { rows, .. } => Some(Cow::Owned(rows.to_string())),
416        }
417    }
418
419    fn param(&self) -> Cow<'_, str> {
420        match self {
421            ResultControl::RowsOffset { rows, offset } => {
422                Cow::Owned(format!("rows={}&offset={}", rows, offset))
423            }
424            _ => {
425                if let Some(val) = self.param_value() {
426                    Cow::Owned(format!("{}={}", self.param_key(), val))
427                } else {
428                    self.param_key()
429                }
430            }
431        }
432    }
433}
434
435/// Major resource components supported by the Crossref API
436#[derive(Debug, Clone, Serialize, Deserialize)]
437#[serde(rename_all = "lowercase")]
438pub enum Component {
439    /// returns a list of all works (journal articles, conference proceedings, books, components, etc), 20 per page
440    Works,
441    /// returns a list of all funders in the [Funder Registry](https://github.com/Crossref/open-funder-registry)
442    Funders,
443    /// returns a list of all Crossref members (mostly publishers)
444    Prefixes,
445    /// returns a list of valid work types
446    Members,
447    /// return a list of licenses applied to works in Crossref metadata
448    Types,
449    /// return a list of journals in the Crossref database
450    Journals,
451}
452
453impl Component {
454    /// identifier for the component route
455    pub fn as_str(&self) -> &str {
456        match self {
457            Component::Works => "works",
458            Component::Funders => "funders",
459            Component::Prefixes => "prefixes",
460            Component::Members => "members",
461            Component::Types => "types",
462            Component::Journals => "journals",
463        }
464    }
465}
466
467impl CrossrefRoute for Component {
468    fn route(&self) -> Result<String> {
469        Ok(format!("/{}", self.as_str()))
470    }
471}
472
473/// bundles all available crossref api endpoints
474#[derive(Debug, Clone)]
475pub enum ResourceComponent {
476    /// returns a list of all works (journal articles, conference proceedings, books, components, etc), 20 per page
477    Works(Works),
478    /// returns a list of all funders in the [Funder Registry](https://github.com/Crossref/open-funder-registry)
479    Funders(Funders),
480    /// returns a list of all Crossref members (mostly publishers)
481    Prefixes(Prefixes),
482    /// returns a list of valid work types
483    Members(Members),
484    /// return a list of licenses applied to works in Crossref metadata
485    Types(Types),
486    /// return a list of journals in the Crossref database
487    Journals(Journals),
488}
489
490impl ResourceComponent {
491    /// the starting crossref component that in the route `/{primary_component}/{id}/works`
492    pub fn primary_component(&self) -> Component {
493        match self {
494            ResourceComponent::Works(_) => Component::Works,
495            ResourceComponent::Funders(_) => Component::Funders,
496            ResourceComponent::Prefixes(_) => Component::Prefixes,
497            ResourceComponent::Members(_) => Component::Members,
498            ResourceComponent::Types(_) => Component::Types,
499            ResourceComponent::Journals(_) => Component::Journals,
500        }
501    }
502}
503
504impl fmt::Display for ResourceComponent {
505    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
506        write!(f, "{}", self.route().map_err(|_| fmt::Error)?)
507    }
508}
509
510impl CrossrefRoute for ResourceComponent {
511    fn route(&self) -> Result<String> {
512        match self {
513            ResourceComponent::Works(c) => c.route(),
514            ResourceComponent::Funders(c) => c.route(),
515            ResourceComponent::Prefixes(c) => c.route(),
516            ResourceComponent::Members(c) => c.route(),
517            ResourceComponent::Types(c) => c.route(),
518            ResourceComponent::Journals(c) => c.route(),
519        }
520    }
521}
522
523impl CrossrefQuery for ResourceComponent {
524    fn resource_component(self) -> ResourceComponent {
525        self
526    }
527}
528
529/// Helper trait to mark filters in the query string
530pub trait Filter: ParamFragment {}
531
532impl<T: Filter> CrossrefQueryParam for Vec<T> {
533    /// always use `filter` as the key
534    fn param_key(&self) -> Cow<'_, str> {
535        Cow::Borrowed("filter")
536    }
537
538    /// filters are multi value and values are concat with `,`
539    fn param_value(&self) -> Option<Cow<'_, str>> {
540        Some(Cow::Owned(
541            self.iter()
542                .map(ParamFragment::fragment)
543                .collect::<Vec<_>>()
544                .join(","),
545        ))
546    }
547}
548
549/// represents a key value pair inside a multi value query string parameter
550pub trait ParamFragment {
551    /// the key, or name, of the fragment
552    fn key(&self) -> Cow<'_, str>;
553
554    /// the value of the fragment, if any
555    fn value(&self) -> Option<Cow<'_, str>>;
556
557    /// key and value are concat using `:`
558    fn fragment(&self) -> Cow<'_, str> {
559        if let Some(val) = self.value() {
560            Cow::Owned(format!("{}:{}", self.key(), val))
561        } else {
562            self.key()
563        }
564    }
565}
566
567/// a trait used to capture parameters for the query string of the crossref api
568pub trait CrossrefQueryParam {
569    /// the key name of the parameter in the query string
570    fn param_key(&self) -> Cow<'_, str>;
571    /// the value of the parameter, if any
572    fn param_value(&self) -> Option<Cow<'_, str>>;
573    /// constructs the full parameter for the query string by combining the key and value
574    fn param(&self) -> Cow<'_, str> {
575        if let Some(val) = self.param_value() {
576            Cow::Owned(format!("{}={}", self.param_key(), val))
577        } else {
578            self.param_key()
579        }
580    }
581}
582
583impl<T: AsRef<str>> CrossrefQueryParam for (T, T) {
584    fn param_key(&self) -> Cow<'_, str> {
585        Cow::Borrowed(self.0.as_ref())
586    }
587
588    fn param_value(&self) -> Option<Cow<'_, str>> {
589        Some(Cow::Borrowed(self.1.as_ref()))
590    }
591}
592
593/// represents elements that constructs parts of the crossref request url
594pub trait CrossrefRoute {
595    /// constructs the route for the crossref api
596    fn route(&self) -> Result<String>;
597}
598
599impl<T: CrossrefQueryParam> CrossrefRoute for dyn AsRef<[T]> {
600    fn route(&self) -> Result<String> {
601        Ok(self
602            .as_ref()
603            .iter()
604            .map(CrossrefQueryParam::param)
605            .collect::<Vec<_>>()
606            .join("&"))
607    }
608}
609
610/// root level trait to construct full crossref api request urls
611pub trait CrossrefQuery: CrossrefRoute + Clone {
612    /// the resource component endpoint this route targets
613    fn resource_component(self) -> ResourceComponent;
614
615    /// constructs the full request url by concating the `base_path` with the `route`
616    fn to_url(&self, base_path: &str) -> Result<String> {
617        Ok(format!("{}{}", base_path, self.route()?))
618    }
619}
620
621/// formats the topic for crossref by replacing all whitespaces with `+`
622pub(crate) fn format_query<T: AsRef<str>>(topic: T) -> String {
623    let mut result = String::new();
624    for (i, word) in topic.as_ref().split_whitespace().enumerate() {
625        if i > 0 {
626            result.push('+');
627        }
628        result.push_str(word);
629    }
630    result
631}
632
633/// formats the individual topics of a query into the format crossref expects
634/// returns a single String consisting of all words combined by '+'
635pub(crate) fn format_queries<T: AsRef<str>>(topics: &[T]) -> String {
636    let mut result = String::new();
637    for topic in topics {
638        for word in topic.as_ref().split_whitespace() {
639            if !result.is_empty() {
640                result.push('+');
641            }
642            result.push_str(word);
643        }
644    }
645    result
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651
652    #[test]
653    fn result_control_rows_offset_param() {
654        let rc = ResultControl::RowsOffset {
655            rows: 10,
656            offset: 5,
657        };
658        let param = rc.param();
659        assert_eq!(param, "rows=10&offset=5");
660    }
661
662    #[test]
663    fn result_control_rows_param() {
664        let rc = ResultControl::Rows(25);
665        assert_eq!(rc.param(), "rows=25");
666    }
667
668    #[test]
669    fn result_control_offset_param() {
670        let rc = ResultControl::Offset(100);
671        assert_eq!(rc.param(), "offset=100");
672    }
673
674    #[test]
675    fn result_control_sample_param() {
676        let rc = ResultControl::Sample(10);
677        assert_eq!(rc.param(), "sample=10");
678    }
679
680    #[test]
681    fn format_query_replaces_whitespace() {
682        assert_eq!(format_query("machine learning"), "machine+learning");
683        assert_eq!(format_query("single"), "single");
684        assert_eq!(format_query("a  b  c"), "a+b+c");
685    }
686
687    #[test]
688    fn format_queries_joins_topics() {
689        assert_eq!(
690            format_queries(&["machine learning", "deep nets"]),
691            "machine+learning+deep+nets"
692        );
693    }
694}