Skip to main content

opencitations_client/
index.rs

1//! The OpenCitations Index: the citation edges themselves.
2//!
3//! Every field of every response arrives as a string, including the ones that
4//! are plainly numbers, dates and booleans, so the types here do the reading
5//! once at the boundary and hand back something already parsed.
6
7use crate::date::{PartialDate, Timespan};
8use crate::id::{Identifier, Oci};
9use serde::{Deserialize, Deserializer, Serialize};
10use std::fmt;
11
12/// One citation: an edge from a citing work to a cited one.
13///
14/// Both ends arrive as the whole bag of identifiers the work is known by, since
15/// which scheme is present varies by source -- reach for
16/// [`Citation::citing_doi`] rather than indexing into them.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Citation {
19    /// the identifier of this citation itself
20    pub oci: Oci,
21    /// every identifier the citing work is known by
22    #[serde(deserialize_with = "bag")]
23    pub citing: Vec<Identifier>,
24    /// every identifier the cited work is known by
25    #[serde(deserialize_with = "bag")]
26    pub cited: Vec<Identifier>,
27    /// when the citing work was published, to whatever precision is recorded
28    #[serde(default, deserialize_with = "blank_is_none")]
29    pub creation: Option<PartialDate>,
30    /// how long after the cited work the citing work appeared; negative when it
31    /// appeared first
32    #[serde(default, deserialize_with = "blank_is_none")]
33    pub timespan: Option<Timespan>,
34    /// whether both works appeared in the same venue
35    #[serde(rename = "journal_sc", deserialize_with = "yes_or_no")]
36    pub journal_self_citation: bool,
37    /// whether the two works share an author
38    #[serde(rename = "author_sc", deserialize_with = "yes_or_no")]
39    pub author_self_citation: bool,
40}
41
42impl Citation {
43    /// The citing work's DOI, when it has one.
44    pub fn citing_doi(&self) -> Option<&str> {
45        self.citing.iter().find_map(Identifier::as_doi)
46    }
47
48    /// The cited work's DOI, when it has one.
49    pub fn cited_doi(&self) -> Option<&str> {
50        self.cited.iter().find_map(Identifier::as_doi)
51    }
52}
53
54/// Reads the space-separated bag of identifiers into all of them.
55fn bag<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Identifier>, D::Error> {
56    let raw = String::deserialize(deserializer)?;
57    Identifier::parse_bag(&raw).map_err(serde::de::Error::custom)
58}
59
60/// Reads a field that is either a value or the empty string OpenCitations uses
61/// where a value is unknown.
62fn blank_is_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
63where
64    D: Deserializer<'de>,
65    T: std::str::FromStr,
66    T::Err: fmt::Display,
67{
68    let raw = String::deserialize(deserializer)?;
69    if raw.trim().is_empty() {
70        return Ok(None);
71    }
72    raw.trim()
73        .parse()
74        .map(Some)
75        .map_err(serde::de::Error::custom)
76}
77
78/// Reads the `yes`/`no` OpenCitations writes where a boolean belongs.
79fn yes_or_no<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
80    let raw = String::deserialize(deserializer)?;
81    match raw.trim().to_ascii_lowercase().as_str() {
82        "yes" | "true" | "1" => Ok(true),
83        "no" | "false" | "0" | "" => Ok(false),
84        other => Err(serde::de::Error::custom(format!(
85            "`{other}` is neither `yes` nor `no`"
86        ))),
87    }
88}
89
90/// The count routes answer with a list holding one object holding one string.
91#[derive(Debug, Deserialize)]
92pub(crate) struct Count {
93    pub(crate) count: String,
94}
95
96/// A field of a [`Citation`], as the api names it.
97///
98/// Used to narrow and to order a listing; the api reads these names in its
99/// `filter` and `sort` parameters.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101#[non_exhaustive]
102pub enum Field {
103    /// the citation's own identifier
104    Oci,
105    /// the citing work's identifiers
106    Citing,
107    /// the cited work's identifiers
108    Cited,
109    /// the citing work's publication date
110    Creation,
111    /// the interval between the two publication dates
112    Timespan,
113    /// whether both works appeared in the same venue
114    JournalSelfCitation,
115    /// whether the two works share an author
116    AuthorSelfCitation,
117}
118
119impl Field {
120    /// The name the api reads this field by.
121    pub fn name(&self) -> &'static str {
122        match self {
123            Field::Oci => "oci",
124            Field::Citing => "citing",
125            Field::Cited => "cited",
126            Field::Creation => "creation",
127            Field::Timespan => "timespan",
128            Field::JournalSelfCitation => "journal_sc",
129            Field::AuthorSelfCitation => "author_sc",
130        }
131    }
132}
133
134impl fmt::Display for Field {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.write_str(self.name())
137    }
138}
139
140/// How a [`Filter`] compares a field against its value.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
142pub enum Comparison {
143    /// the field is exactly the value
144    #[default]
145    Is,
146    /// the field sorts after the value
147    GreaterThan,
148    /// the field sorts before the value
149    LessThan,
150}
151
152impl Comparison {
153    fn prefix(&self) -> &'static str {
154        match self {
155            Comparison::Is => "",
156            Comparison::GreaterThan => ">",
157            Comparison::LessThan => "<",
158        }
159    }
160}
161
162/// A narrowing applied by the api rather than by the caller.
163///
164/// Worth preferring over filtering the results here: a well cited work has
165/// thousands of citations and they arrive in one unpaged response.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct Filter {
168    field: Field,
169    comparison: Comparison,
170    value: String,
171}
172
173impl Filter {
174    /// The citations whose `field` is exactly `value`.
175    pub fn is(field: Field, value: impl Into<String>) -> Self {
176        Filter {
177            field,
178            comparison: Comparison::Is,
179            value: value.into(),
180        }
181    }
182
183    /// The citations whose `field` sorts after `value`, e.g. everything created
184    /// after a given year.
185    pub fn greater_than(field: Field, value: impl Into<String>) -> Self {
186        Filter {
187            field,
188            comparison: Comparison::GreaterThan,
189            value: value.into(),
190        }
191    }
192
193    /// The citations whose `field` sorts before `value`.
194    pub fn less_than(field: Field, value: impl Into<String>) -> Self {
195        Filter {
196            field,
197            comparison: Comparison::LessThan,
198            value: value.into(),
199        }
200    }
201}
202
203impl fmt::Display for Filter {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        write!(
206            f,
207            "{}:{}{}",
208            self.field,
209            self.comparison.prefix(),
210            self.value
211        )
212    }
213}
214
215/// Which way a [`Sort`] runs.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
217pub enum Order {
218    /// earliest, or lowest, first
219    #[default]
220    Ascending,
221    /// latest, or highest, first
222    Descending,
223}
224
225/// The order the api returns a listing in.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct Sort {
228    field: Field,
229    order: Order,
230}
231
232impl Sort {
233    /// Earliest, or lowest, first.
234    pub fn ascending(field: Field) -> Self {
235        Sort {
236            field,
237            order: Order::Ascending,
238        }
239    }
240
241    /// Latest, or highest, first.
242    pub fn descending(field: Field) -> Self {
243        Sort {
244            field,
245            order: Order::Descending,
246        }
247    }
248}
249
250impl fmt::Display for Sort {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        let order = match self.order {
253            Order::Ascending => "asc",
254            Order::Descending => "desc",
255        };
256        write!(f, "{order}({})", self.field)
257    }
258}
259
260/// What to ask of a citation listing beyond the identifier itself.
261///
262/// The api applies all of it before answering, so a narrow listing is one
263/// response rather than one response and a lot of discarding.
264///
265/// ```
266/// use opencitations_client::{Field, Filter, Refine, Sort};
267///
268/// // the citations this work picked up since 2024, earliest first
269/// let refine = Refine::new()
270///     .filter(Filter::greater_than(Field::Creation, "2023"))
271///     .sort(Sort::ascending(Field::Creation));
272/// ```
273#[derive(Debug, Clone, Default, PartialEq, Eq)]
274pub struct Refine {
275    filters: Vec<Filter>,
276    sort: Option<Sort>,
277}
278
279impl Refine {
280    /// Asks for everything, in whatever order the api answers in.
281    pub fn new() -> Self {
282        Refine::default()
283    }
284
285    /// Narrows the listing. Repeating this ANDs the filters.
286    pub fn filter(mut self, filter: Filter) -> Self {
287        self.filters.push(filter);
288        self
289    }
290
291    /// Orders the listing. The last one set wins.
292    pub fn sort(mut self, sort: Sort) -> Self {
293        self.sort = Some(sort);
294        self
295    }
296
297    /// Whether this asks for anything at all.
298    pub fn is_empty(&self) -> bool {
299        self.filters.is_empty() && self.sort.is_none()
300    }
301
302    /// The query parameters this renders to, ready to be percent-encoded.
303    pub(crate) fn params(&self) -> Vec<(&'static str, String)> {
304        let filters = self
305            .filters
306            .iter()
307            .map(|filter| ("filter", filter.to_string()));
308        let sort = self.sort.map(|sort| ("sort", sort.to_string()));
309        filters.chain(sort).collect()
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    /// The shape the api actually answers with, as captured from
318    /// `/index/v2/citations/doi:10.1016/j.marpol.2021.104855`.
319    const WIRE: &str = r#"{
320        "oci": "06024047477-06220256775",
321        "citing": "omid:br/06024047477 doi:10.22533/at.ed.9662430046",
322        "cited": "omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
323        "creation": "2024",
324        "timespan": "P2Y",
325        "journal_sc": "no",
326        "author_sc": "no"
327    }"#;
328
329    #[test]
330    fn a_citation_reads_every_stringly_typed_field() {
331        let citation: Citation = serde_json::from_str(WIRE).unwrap();
332
333        assert_eq!(citation.oci.to_string(), "06024047477-06220256775");
334        assert_eq!(citation.citing_doi(), Some("10.22533/at.ed.9662430046"));
335        assert_eq!(citation.cited_doi(), Some("10.1016/j.marpol.2021.104855"));
336        assert_eq!(citation.creation.unwrap().year(), 2024);
337        assert_eq!(citation.timespan.unwrap().as_months(), 24);
338        assert!(!citation.journal_self_citation);
339        assert!(!citation.author_self_citation);
340        // the bag keeps every scheme, not just the doi
341        assert_eq!(citation.cited.len(), 3);
342    }
343
344    #[test]
345    fn an_unknown_creation_or_timespan_is_none_rather_than_an_error() {
346        let wire = WIRE.replace(r#""creation": "2024""#, r#""creation": """#);
347        let wire = wire.replace(r#""timespan": "P2Y""#, r#""timespan": """#);
348
349        let citation: Citation = serde_json::from_str(&wire).unwrap();
350        assert_eq!(citation.creation, None);
351        assert_eq!(citation.timespan, None);
352    }
353
354    #[test]
355    fn a_self_citation_reads_as_the_boolean_it_is() {
356        let wire = WIRE.replace(r#""author_sc": "no""#, r#""author_sc": "yes""#);
357        let citation: Citation = serde_json::from_str(&wire).unwrap();
358        assert!(citation.author_self_citation);
359    }
360
361    #[test]
362    fn a_refinement_renders_the_parameters_the_api_reads() {
363        let refine = Refine::new()
364            .filter(Filter::greater_than(Field::Creation, "2023"))
365            .filter(Filter::is(Field::AuthorSelfCitation, "no"))
366            .sort(Sort::descending(Field::Timespan));
367
368        assert_eq!(
369            refine.params(),
370            vec![
371                ("filter", "creation:>2023".to_string()),
372                ("filter", "author_sc:no".to_string()),
373                ("sort", "desc(timespan)".to_string()),
374            ]
375        );
376    }
377
378    #[test]
379    fn an_empty_refinement_asks_for_nothing() {
380        assert!(Refine::new().is_empty());
381        assert!(Refine::new().params().is_empty());
382    }
383}