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
16pub(crate) trait FilterValue: Sized {
23 fn render(&self) -> Cow<'_, str>;
25
26 fn parse(value: &str) -> Option<Self>;
29}
30
31impl FilterValue for String {
32 fn render(&self) -> Cow<'_, str> {
33 Cow::Borrowed(self)
34 }
35
36 fn parse(value: &str) -> Option<Self> {
37 Some(value.to_string())
38 }
39}
40
41impl FilterValue for i32 {
42 fn render(&self) -> Cow<'_, str> {
43 Cow::Owned(self.to_string())
44 }
45
46 fn parse(value: &str) -> Option<Self> {
47 value.parse().ok()
48 }
49}
50
51impl FilterValue for u64 {
52 fn render(&self) -> Cow<'_, str> {
53 Cow::Owned(self.to_string())
54 }
55
56 fn parse(value: &str) -> Option<Self> {
57 value.parse().ok()
58 }
59}
60
61impl FilterValue for chrono::NaiveDate {
62 fn render(&self) -> Cow<'_, str> {
63 Cow::Owned(self.format("%Y-%m-%d").to_string())
64 }
65
66 fn parse(value: &str) -> Option<Self> {
67 chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").ok()
68 }
69}
70
71impl FilterValue for types::Type {
72 fn render(&self) -> Cow<'_, str> {
73 Cow::Borrowed(self.id())
74 }
75
76 fn parse(value: &str) -> Option<Self> {
77 value.parse().ok()
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
87pub enum FilterParseError {
88 #[error("`{name}` is not a filter this route takes")]
90 UnknownName {
91 name: String,
93 },
94 #[error("`{name}` takes no value; it asks only whether the record has one")]
97 MarkerWithValue {
98 name: String,
100 },
101 #[error("`{name}` needs a value, as `{name}:<value>`")]
103 MissingValue {
104 name: String,
106 },
107 #[error("`{value}` is not a value `{name}` can narrow by")]
110 UnreadableValue {
111 name: String,
113 value: String,
115 },
116}
117
118macro_rules! define_filter {
125 (
126 $(#[$meta:meta])*
127 $name:ident;
128 markers { $($(#[$m_doc:meta])* $m_variant:ident => $m_key:literal,)* }
129 values { $($(#[$v_doc:meta])* $v_variant:ident($v_ty:ty) => $v_key:literal,)* }
130 ) => {
131 $(#[$meta])*
132 #[derive(Debug, Clone, PartialEq, Eq)]
133 pub enum $name {
134 $($(#[$m_doc])* $m_variant,)*
135 $($(#[$v_doc])* $v_variant($v_ty),)*
136 }
137
138 impl $name {
139 pub const ALL_NAMES: &'static [&'static str] = &[$($m_key,)* $($v_key,)*];
145
146 pub fn name(&self) -> &'static str {
148 match self {
149 $($name::$m_variant => $m_key,)*
150 $($name::$v_variant(_) => $v_key,)*
151 }
152 }
153
154 pub fn from_name(
163 name: &str,
164 value: Option<&str>,
165 ) -> ::std::result::Result<Self, $crate::query::FilterParseError> {
166 use $crate::query::{FilterParseError, FilterValue};
167
168 match name {
169 $($m_key => match value {
170 None | Some("true") => Ok($name::$m_variant),
171 Some(_) => Err(FilterParseError::MarkerWithValue {
172 name: name.to_string(),
173 }),
174 },)*
175 $($v_key => match value {
176 None => Err(FilterParseError::MissingValue { name: name.to_string() }),
177 Some(value) => <$v_ty as FilterValue>::parse(value)
178 .map($name::$v_variant)
179 .ok_or_else(|| FilterParseError::UnreadableValue {
180 name: name.to_string(),
181 value: value.to_string(),
182 }),
183 },)*
184 _ => Err(FilterParseError::UnknownName { name: name.to_string() }),
185 }
186 }
187 }
188
189 impl $crate::query::ParamFragment for $name {
190 fn key(&self) -> ::std::borrow::Cow<'_, str> {
191 ::std::borrow::Cow::Borrowed(self.name())
192 }
193
194 fn value(&self) -> Option<::std::borrow::Cow<'_, str>> {
195 match self {
196 $($name::$m_variant => Some(::std::borrow::Cow::Borrowed("true")),)*
197 $($name::$v_variant(value) => {
198 Some($crate::query::FilterValue::render(value))
199 })*
200 }
201 }
202 }
203
204 impl $crate::query::Filter for $name {}
205 };
206}
207
208macro_rules! impl_list_query {
216 ($(#[$meta:meta])* $name:ident $(, filter = $filter:ident)?) => {
217 $(#[$meta])*
218 #[derive(Debug, Clone, Default, PartialEq, Eq)]
219 pub struct $name {
220 pub queries: Vec<String>,
222 $(
223 pub filter: Vec<$filter>,
225 )?
226 pub result_control: Option<ResultControl>,
231 }
232
233 impl $name {
234 $(
235 pub fn filter(mut self, filter: $filter) -> Self {
237 self.filter.push(filter);
238 self
239 }
240 )?
241 pub fn empty() -> Self {
243 Self::default()
244 }
245
246 pub fn new<T: ToString>(query: T) -> Self {
248 Self::empty().query(query)
249 }
250
251 pub fn query<T: ToString>(mut self, query: T) -> Self {
253 self.queries.push(query.to_string());
254 self
255 }
256
257 pub fn queries<T: ToString>(mut self, queries: &[T]) -> Self {
259 self.queries.extend(queries.iter().map(T::to_string));
260 self
261 }
262
263 pub fn result_control(
265 mut self,
266 result_control: impl Into<Option<ResultControl>>,
267 ) -> Self {
268 self.result_control = result_control.into();
269 self
270 }
271 }
272
273 impl CrossrefRoute for $name {
274 fn route(&self) -> Result<String> {
275 let mut params: Vec<(Cow<'_, str>, Cow<'_, str>)> = Vec::new();
276 if !self.queries.is_empty() {
277 params.push((
278 Cow::Borrowed("query"),
279 Cow::Owned(format_queries(&self.queries)),
280 ));
281 }
282 $(
283 let filters: &[$filter] = &self.filter;
284 if !filters.is_empty() {
285 $crate::query::reject_unsendable_filters(filters)?;
286 params.extend(self.filter.params());
287 }
288 )?
289 if let Some(rc) = &self.result_control {
290 params.extend(rc.params());
291 }
292 Ok(encode::query_string(¶ms))
293 }
294 }
295 };
296}
297
298macro_rules! define_keyed_enum {
301 (
302 $(#[$meta:meta])*
303 $name:ident { $($(#[$doc:meta])* $variant:ident => $key:literal,)* }
304 ) => {
305 $(#[$meta])*
306 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
307 pub enum $name {
308 $(
309 #[doc = concat!("the `", $key, "` field")]
310 $(#[$doc])*
311 $variant,
312 )*
313 }
314
315 impl $name {
316 pub fn name(&self) -> &'static str {
318 match self { $($name::$variant => $key,)* }
319 }
320
321 pub const ALL: &'static [$name] = &[$($name::$variant,)*];
323 }
324 };
325}
326
327macro_rules! define_field_queries {
333 ($($(#[$doc:meta])* $variant:ident => $key:literal / $ctor:ident,)*) => {
334 #[derive(Debug, Clone, PartialEq, Eq)]
346 pub enum FieldQuery {
347 $(
348 #[doc = concat!("matches against `", $key, "`: ")]
349 $(#[$doc])*
350 $variant(String),
351 )*
352 }
353
354 impl FieldQuery {
355 pub const ALL_FIELDS: &'static [&'static str] = &[$($key,)*];
358
359 pub fn name(&self) -> &'static str {
361 match self { $(FieldQuery::$variant(_) => concat!("query.", $key),)* }
362 }
363
364 pub fn field(&self) -> &'static str {
366 match self { $(FieldQuery::$variant(_) => $key,)* }
367 }
368
369 pub fn value(&self) -> &str {
371 match self { $(FieldQuery::$variant(value) => value,)* }
372 }
373
374 pub fn from_field(field: &str, value: impl Into<String>) -> Option<Self> {
389 match field {
390 $($key => Some(FieldQuery::$variant(value.into())),)*
391 _ => None,
392 }
393 }
394
395 $(
396 #[doc = concat!("a query against `", $key, "`")]
397 pub fn $ctor(value: impl Into<String>) -> Self {
398 FieldQuery::$variant(value.into())
399 }
400 )*
401 }
402 };
403}
404
405pub(crate) mod encode;
407pub mod facet;
409pub mod funders;
411pub mod journals;
413pub mod licenses;
415pub mod members;
417pub mod prefixes;
419pub mod types;
421pub mod works;
423
424#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
426#[serde(rename_all = "kebab-case")]
427pub enum Visibility {
428 Open,
430 Limited,
432 Closed,
434}
435
436impl Visibility {
437 pub fn as_str(&self) -> &str {
439 match self {
440 Visibility::Open => "open",
441 Visibility::Limited => "limited",
442 Visibility::Closed => "closed",
443 }
444 }
445}
446
447#[derive(Debug, PartialEq, Eq, Clone, Copy)]
449pub enum Order {
450 Asc,
452 Desc,
454}
455
456impl Order {
457 pub fn as_str(&self) -> &str {
459 match self {
460 Order::Asc => "asc",
461 Order::Desc => "desc",
462 }
463 }
464}
465
466impl FromStr for Order {
467 type Err = String;
468
469 fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
470 match s {
471 "asc" => Ok(Order::Asc),
472 "desc" => Ok(Order::Desc),
473 other => Err(format!("Unable to convert {} to Order", other)),
474 }
475 }
476}
477
478impl CrossrefQueryParam for Order {
479 fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
480 vec![(Cow::Borrowed("order"), Cow::Borrowed(self.as_str()))]
481 }
482}
483
484#[derive(Debug, PartialEq, Eq, Clone, Copy)]
486pub enum Sort {
487 Score,
489 Updated,
491 Deposited,
493 Indexed,
495 Published,
497 PublishedPrint,
499 PublishedOnline,
501 Issued,
503 IsReferencedByCount,
505 ReferenceCount,
507 Created,
509 Relevance,
511}
512
513impl Sort {
514 pub const ALL: &'static [Sort] = &[
516 Sort::Score,
517 Sort::Updated,
518 Sort::Deposited,
519 Sort::Indexed,
520 Sort::Published,
521 Sort::PublishedPrint,
522 Sort::PublishedOnline,
523 Sort::Issued,
524 Sort::IsReferencedByCount,
525 Sort::ReferenceCount,
526 Sort::Created,
527 Sort::Relevance,
528 ];
529
530 pub fn as_str(&self) -> &str {
532 match self {
533 Sort::Score => "score",
534 Sort::Updated => "updated",
535 Sort::Deposited => "deposited",
536 Sort::Indexed => "indexed",
537 Sort::Published => "published",
538 Sort::PublishedPrint => "published-print",
539 Sort::PublishedOnline => "published-online",
540 Sort::Issued => "issued",
541 Sort::IsReferencedByCount => "is-referenced-by-count",
542 Sort::ReferenceCount => "references-count",
543 Sort::Created => "created",
544 Sort::Relevance => "relevance",
545 }
546 }
547}
548
549impl FromStr for Sort {
550 type Err = String;
551
552 fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
553 match s {
554 "score" => Ok(Sort::Score),
555 "updated" => Ok(Sort::Updated),
556 "deposited" => Ok(Sort::Deposited),
557 "indexed" => Ok(Sort::Indexed),
558 "published" => Ok(Sort::Published),
559 "published-print" => Ok(Sort::PublishedPrint),
560 "published-online" => Ok(Sort::PublishedOnline),
561 "issued" => Ok(Sort::Issued),
562 "is-referenced-by-count" => Ok(Sort::IsReferencedByCount),
563 "references-count" => Ok(Sort::ReferenceCount),
564 "created" => Ok(Sort::Created),
565 "relevance" => Ok(Sort::Relevance),
566 other => Err(format!("Unable to convert {} to Sort", other)),
567 }
568 }
569}
570
571impl CrossrefQueryParam for Sort {
572 fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
573 vec![(Cow::Borrowed("sort"), Cow::Borrowed(self.as_str()))]
574 }
575}
576
577#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579pub enum ResultControl {
580 Rows(usize),
582 Offset(usize),
585 RowsOffset {
587 rows: usize,
589 offset: usize,
591 },
592 Sample(usize),
594}
595
596impl CrossrefQueryParam for ResultControl {
597 fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
598 match self {
599 ResultControl::Rows(rows) => {
600 vec![(Cow::Borrowed("rows"), Cow::Owned(rows.to_string()))]
601 }
602 ResultControl::Offset(offset) => {
603 vec![(Cow::Borrowed("offset"), Cow::Owned(offset.to_string()))]
604 }
605 ResultControl::RowsOffset { rows, offset } => vec![
606 (Cow::Borrowed("rows"), Cow::Owned(rows.to_string())),
607 (Cow::Borrowed("offset"), Cow::Owned(offset.to_string())),
608 ],
609 ResultControl::Sample(sample) => {
610 vec![(Cow::Borrowed("sample"), Cow::Owned(sample.to_string()))]
611 }
612 }
613 }
614}
615
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
618#[serde(rename_all = "lowercase")]
619pub enum Component {
620 Works,
622 Funders,
624 Prefixes,
626 Members,
628 Types,
630 Journals,
632 Licenses,
634}
635
636impl Component {
637 pub fn as_str(&self) -> &str {
639 match self {
640 Component::Works => "works",
641 Component::Funders => "funders",
642 Component::Prefixes => "prefixes",
643 Component::Members => "members",
644 Component::Types => "types",
645 Component::Journals => "journals",
646 Component::Licenses => "licenses",
647 }
648 }
649}
650
651impl CrossrefRoute for Component {
652 fn route(&self) -> Result<String> {
653 Ok(format!("/{}", self.as_str()))
654 }
655}
656
657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
662pub enum WorksComponent {
663 Funders,
665 Prefixes,
667 Members,
669 Types,
671 Journals,
673}
674
675impl WorksComponent {
676 pub fn component(&self) -> Component {
678 match self {
679 WorksComponent::Funders => Component::Funders,
680 WorksComponent::Prefixes => Component::Prefixes,
681 WorksComponent::Members => Component::Members,
682 WorksComponent::Types => Component::Types,
683 WorksComponent::Journals => Component::Journals,
684 }
685 }
686}
687
688impl CrossrefRoute for WorksComponent {
689 fn route(&self) -> Result<String> {
690 self.component().route()
691 }
692}
693
694#[derive(Debug, Clone)]
696pub enum ResourceComponent {
697 Works(Works),
699 Funders(Funders),
701 Prefixes(Prefixes),
703 Members(Members),
705 Types(Types),
707 Journals(Journals),
709 Licenses(Licenses),
711}
712
713impl ResourceComponent {
714 pub fn primary_component(&self) -> Component {
716 match self {
717 ResourceComponent::Works(_) => Component::Works,
718 ResourceComponent::Funders(_) => Component::Funders,
719 ResourceComponent::Prefixes(_) => Component::Prefixes,
720 ResourceComponent::Members(_) => Component::Members,
721 ResourceComponent::Types(_) => Component::Types,
722 ResourceComponent::Journals(_) => Component::Journals,
723 ResourceComponent::Licenses(_) => Component::Licenses,
724 }
725 }
726}
727
728impl fmt::Display for ResourceComponent {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730 write!(f, "{}", self.route().map_err(|_| fmt::Error)?)
731 }
732}
733
734impl CrossrefRoute for ResourceComponent {
735 fn route(&self) -> Result<String> {
736 match self {
737 ResourceComponent::Works(c) => c.route(),
738 ResourceComponent::Funders(c) => c.route(),
739 ResourceComponent::Prefixes(c) => c.route(),
740 ResourceComponent::Members(c) => c.route(),
741 ResourceComponent::Types(c) => c.route(),
742 ResourceComponent::Journals(c) => c.route(),
743 ResourceComponent::Licenses(c) => c.route(),
744 }
745 }
746}
747
748impl CrossrefQuery for ResourceComponent {
749 fn resource_component(self) -> ResourceComponent {
750 self
751 }
752}
753
754pub trait Filter: ParamFragment {}
756
757impl<T: Filter> CrossrefQueryParam for Vec<T> {
758 fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
760 vec![(
761 Cow::Borrowed("filter"),
762 Cow::Owned(
763 self.iter()
764 .map(ParamFragment::fragment)
765 .collect::<Vec<_>>()
766 .join(","),
767 ),
768 )]
769 }
770}
771
772pub trait ParamFragment {
774 fn key(&self) -> Cow<'_, str>;
776
777 fn value(&self) -> Option<Cow<'_, str>>;
779
780 fn fragment(&self) -> Cow<'_, str> {
782 if let Some(val) = self.value() {
783 Cow::Owned(format!("{}:{}", self.key(), val))
784 } else {
785 self.key()
786 }
787 }
788}
789
790pub trait CrossrefQueryParam {
792 fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)>;
800}
801
802impl<T: AsRef<str>> CrossrefQueryParam for (T, T) {
803 fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
804 vec![(
805 Cow::Borrowed(self.0.as_ref()),
806 Cow::Borrowed(self.1.as_ref()),
807 )]
808 }
809}
810
811pub trait CrossrefRoute {
813 fn route(&self) -> Result<String>;
815}
816
817pub trait CrossrefQuery: CrossrefRoute + Clone {
819 fn resource_component(self) -> ResourceComponent;
821
822 fn to_url(&self, base_path: &str) -> Result<String> {
824 Ok(format!("{}{}", base_path, self.route()?))
825 }
826}
827
828pub(crate) fn reject_unsendable_filters<T: Filter>(filters: &[T]) -> Result<()> {
837 for filter in filters {
838 match filter.value() {
839 Some(value) if value.contains(',') => {
840 return Err(crate::Error::UnsendableFilterValue {
841 filter: filter.key().into_owned(),
842 value: value.into_owned(),
843 });
844 }
845 _ => (),
846 }
847 }
848 Ok(())
849}
850
851pub(crate) fn format_query<T: AsRef<str>>(topic: T) -> String {
858 topic
859 .as_ref()
860 .split_whitespace()
861 .collect::<Vec<_>>()
862 .join(" ")
863}
864
865pub(crate) fn format_queries<T: AsRef<str>>(topics: &[T]) -> String {
867 topics
868 .iter()
869 .flat_map(|topic| topic.as_ref().split_whitespace())
870 .collect::<Vec<_>>()
871 .join(" ")
872}
873
874#[cfg(test)]
882fn assert_matches_api(kind: &str, ours: &[&str], api: &[&str]) {
883 use std::collections::BTreeSet;
884
885 let mine: BTreeSet<&str> = ours.iter().copied().collect();
886 assert_eq!(ours.len(), mine.len(), "duplicate {kind} in this crate");
887
888 let theirs: BTreeSet<&str> = api.iter().copied().collect();
889 assert_eq!(api.len(), theirs.len(), "duplicate {kind} in the api list");
890
891 let rejected: Vec<_> = mine.difference(&theirs).collect();
892 assert!(
893 rejected.is_empty(),
894 "{kind} this crate sends that crossref answers with a 400: {rejected:?}"
895 );
896
897 let unreachable: Vec<_> = theirs.difference(&mine).collect();
898 assert!(
899 unreachable.is_empty(),
900 "{kind} crossref accepts that this crate cannot express: {unreachable:?}"
901 );
902}
903
904#[cfg(test)]
905mod tests {
906 use super::*;
907 use crate::query::funders::FundersFilter;
908 use crate::query::members::MembersFilter;
909 use crate::query::works::{FieldQuery, WorkElement, WorksFilter};
910
911 const API_SORT_FIELDS: &[&str] = &[
913 "score",
914 "created",
915 "issued",
916 "indexed",
917 "is-referenced-by-count",
918 "relevance",
919 "published",
920 "published-print",
921 "published-online",
922 "updated",
923 "references-count",
924 "deposited",
925 ];
926
927 #[test]
928 fn every_sort_key_is_accepted_by_the_api() {
929 let names: Vec<&str> = Sort::ALL.iter().map(Sort::as_str).collect();
930
931 assert_matches_api("/works sort fields", &names, API_SORT_FIELDS);
932 }
933
934 #[test]
935 fn sort_round_trips_through_from_str() {
936 for sort in Sort::ALL {
937 assert_eq!(Ok(*sort), Sort::from_str(sort.as_str()));
938 }
939 }
940
941 #[test]
942 fn order_round_trips_through_from_str() {
943 for order in [Order::Asc, Order::Desc] {
944 assert_eq!(Ok(order), Order::from_str(order.as_str()));
945 }
946 }
947
948 const API_WORKS_FILTERS: &[&str] = &[
950 "alternative-id",
951 "archive",
952 "article-number",
953 "assertion",
954 "assertion-group",
955 "award.funder",
956 "award.number",
957 "category-name",
958 "clinical-trial-number",
959 "container-title",
960 "content-domain",
961 "directory",
962 "doi",
963 "from-accepted-date",
964 "from-approved-date",
965 "from-awarded-date",
966 "from-created-date",
967 "from-deposit-date",
968 "from-event-end-date",
969 "from-event-start-date",
970 "from-index-date",
971 "from-issued-date",
972 "from-online-pub-date",
973 "from-posted-date",
974 "from-print-pub-date",
975 "from-pub-date",
976 "from-update-date",
977 "full-text.application",
978 "full-text.type",
979 "full-text.version",
980 "funder",
981 "funder-doi-asserted-by",
982 "group-title",
983 "gte-award-amount",
984 "has-abstract",
985 "has-affiliation",
986 "has-affiliation-ror-id",
987 "has-alias",
988 "has-archive",
989 "has-assertion",
990 "has-authenticated-orcid",
991 "has-award",
992 "has-clinical-trial-number",
993 "has-content-domain",
994 "has-domain-restriction",
995 "has-event",
996 "has-full-text",
997 "has-funder",
998 "has-funder-doi",
999 "has-funder-ror-id",
1000 "has-license",
1001 "has-orcid",
1002 "has-prime-doi",
1003 "has-references",
1004 "has-relation",
1005 "has-ror-id",
1006 "has-update",
1007 "has-update-policy",
1008 "is-update",
1009 "isbn",
1010 "issn",
1011 "license.delay",
1012 "license.url",
1013 "license.version",
1014 "lte-award-amount",
1015 "member",
1016 "orcid",
1017 "prefix",
1018 "relation.object",
1019 "relation.object-type",
1020 "relation.type",
1021 "ror-id",
1022 "type",
1023 "type-name",
1024 "until-accepted-date",
1025 "until-approved-date",
1026 "until-awarded-date",
1027 "until-created-date",
1028 "until-deposit-date",
1029 "until-event-end-date",
1030 "until-event-start-date",
1031 "until-index-date",
1032 "until-issued-date",
1033 "until-online-pub-date",
1034 "until-posted-date",
1035 "until-print-pub-date",
1036 "until-pub-date",
1037 "until-update-date",
1038 "update-type",
1039 "updates",
1040 ];
1041
1042 const API_FIELD_QUERIES: &[&str] = &[
1044 "affiliation",
1045 "author",
1046 "bibliographic",
1047 "chair",
1048 "container-title",
1049 "contributor",
1050 "degree",
1051 "description",
1052 "editor",
1053 "event-acronym",
1054 "event-location",
1055 "event-name",
1056 "event-sponsor",
1057 "event-theme",
1058 "funder-name",
1059 "publisher-location",
1060 "publisher-name",
1061 "standards-body-acronym",
1062 "standards-body-name",
1063 "title",
1064 "translator",
1065 ];
1066
1067 const API_WORK_ELEMENTS: &[&str] = &[
1069 "DOI",
1070 "ISBN",
1071 "ISSN",
1072 "URL",
1073 "abstract",
1074 "accepted",
1075 "alternative-id",
1076 "approved",
1077 "archive",
1078 "article-number",
1079 "assertion",
1080 "author",
1081 "chair",
1082 "clinical-trial-number",
1083 "container-title",
1084 "content-created",
1085 "content-domain",
1086 "contributor",
1087 "created",
1088 "degree",
1089 "deposited",
1090 "editor",
1091 "event",
1092 "funder",
1093 "group-title",
1094 "indexed",
1095 "is-referenced-by-count",
1096 "issn-type",
1097 "issue",
1098 "issued",
1099 "license",
1100 "link",
1101 "member",
1102 "original-title",
1103 "page",
1104 "posted",
1105 "prefix",
1106 "published",
1107 "published-online",
1108 "published-print",
1109 "publisher",
1110 "publisher-location",
1111 "reference",
1112 "references-count",
1113 "relation",
1114 "resource",
1115 "score",
1116 "short-container-title",
1117 "short-title",
1118 "standards-body",
1119 "subject",
1120 "subtitle",
1121 "title",
1122 "translator",
1123 "type",
1124 "update-policy",
1125 "update-to",
1126 "updated-by",
1127 "volume",
1128 ];
1129
1130 const API_FUNDERS_FILTERS: &[&str] = &["location"];
1132
1133 const API_MEMBERS_FILTERS: &[&str] = &["prefix", "backfile-doi-count", "current-doi-count"];
1135
1136 #[test]
1137 fn every_works_filter_is_accepted_by_the_api() {
1138 assert_matches_api("/works filters", WorksFilter::ALL_NAMES, API_WORKS_FILTERS);
1139 }
1140
1141 #[test]
1142 fn every_field_query_is_accepted_by_the_api() {
1143 assert_matches_api(
1144 "/works field queries",
1145 FieldQuery::ALL_FIELDS,
1146 API_FIELD_QUERIES,
1147 );
1148 }
1149
1150 #[test]
1151 fn every_selectable_element_is_accepted_by_the_api() {
1152 let names: Vec<&str> = WorkElement::ALL.iter().map(WorkElement::name).collect();
1153
1154 assert_matches_api("/works select elements", &names, API_WORK_ELEMENTS);
1155 }
1156
1157 #[test]
1158 fn every_funders_filter_is_accepted_by_the_api() {
1159 assert_matches_api(
1160 "/funders filters",
1161 FundersFilter::ALL_NAMES,
1162 API_FUNDERS_FILTERS,
1163 );
1164 }
1165
1166 #[test]
1167 fn every_members_filter_is_accepted_by_the_api() {
1168 assert_matches_api(
1169 "/members filters",
1170 MembersFilter::ALL_NAMES,
1171 API_MEMBERS_FILTERS,
1172 );
1173 }
1174
1175 #[test]
1176 fn a_marker_filter_renders_as_true_and_a_value_filter_as_its_value() {
1177 let filters = vec![
1178 WorksFilter::HasOrcid,
1179 WorksFilter::AlternativeId("abc".to_string()),
1180 WorksFilter::LicenseDelay(30),
1181 WorksFilter::GteAwardAmount(1_000),
1182 ];
1183
1184 assert_eq!(
1185 vec![(
1186 Cow::Borrowed("filter"),
1187 Cow::Owned(
1188 "has-orcid:true,alternative-id:abc,license.delay:30,gte-award-amount:1000"
1189 .to_string()
1190 )
1191 )],
1192 filters.params()
1193 );
1194 }
1195}