use crate::date::{PartialDate, Timespan};
use crate::id::{Identifier, Oci};
use serde::{Deserialize, Deserializer, Serialize};
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Citation {
pub oci: Oci,
#[serde(deserialize_with = "bag")]
pub citing: Vec<Identifier>,
#[serde(deserialize_with = "bag")]
pub cited: Vec<Identifier>,
#[serde(default, deserialize_with = "blank_is_none")]
pub creation: Option<PartialDate>,
#[serde(default, deserialize_with = "blank_is_none")]
pub timespan: Option<Timespan>,
#[serde(rename = "journal_sc", deserialize_with = "yes_or_no")]
pub journal_self_citation: bool,
#[serde(rename = "author_sc", deserialize_with = "yes_or_no")]
pub author_self_citation: bool,
}
impl Citation {
pub fn citing_doi(&self) -> Option<&str> {
self.citing.iter().find_map(Identifier::as_doi)
}
pub fn cited_doi(&self) -> Option<&str> {
self.cited.iter().find_map(Identifier::as_doi)
}
}
fn bag<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Identifier>, D::Error> {
let raw = String::deserialize(deserializer)?;
Identifier::parse_bag(&raw).map_err(serde::de::Error::custom)
}
fn blank_is_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: std::str::FromStr,
T::Err: fmt::Display,
{
let raw = String::deserialize(deserializer)?;
if raw.trim().is_empty() {
return Ok(None);
}
raw.trim()
.parse()
.map(Some)
.map_err(serde::de::Error::custom)
}
fn yes_or_no<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
let raw = String::deserialize(deserializer)?;
match raw.trim().to_ascii_lowercase().as_str() {
"yes" | "true" | "1" => Ok(true),
"no" | "false" | "0" | "" => Ok(false),
other => Err(serde::de::Error::custom(format!(
"`{other}` is neither `yes` nor `no`"
))),
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct Count {
pub(crate) count: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Field {
Oci,
Citing,
Cited,
Creation,
Timespan,
JournalSelfCitation,
AuthorSelfCitation,
}
impl Field {
pub fn name(&self) -> &'static str {
match self {
Field::Oci => "oci",
Field::Citing => "citing",
Field::Cited => "cited",
Field::Creation => "creation",
Field::Timespan => "timespan",
Field::JournalSelfCitation => "journal_sc",
Field::AuthorSelfCitation => "author_sc",
}
}
}
impl fmt::Display for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Comparison {
#[default]
Is,
GreaterThan,
LessThan,
}
impl Comparison {
fn prefix(&self) -> &'static str {
match self {
Comparison::Is => "",
Comparison::GreaterThan => ">",
Comparison::LessThan => "<",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Filter {
field: Field,
comparison: Comparison,
value: String,
}
impl Filter {
pub fn is(field: Field, value: impl Into<String>) -> Self {
Filter {
field,
comparison: Comparison::Is,
value: value.into(),
}
}
pub fn greater_than(field: Field, value: impl Into<String>) -> Self {
Filter {
field,
comparison: Comparison::GreaterThan,
value: value.into(),
}
}
pub fn less_than(field: Field, value: impl Into<String>) -> Self {
Filter {
field,
comparison: Comparison::LessThan,
value: value.into(),
}
}
}
impl fmt::Display for Filter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}:{}{}",
self.field,
self.comparison.prefix(),
self.value
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
#[default]
Ascending,
Descending,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sort {
field: Field,
order: Order,
}
impl Sort {
pub fn ascending(field: Field) -> Self {
Sort {
field,
order: Order::Ascending,
}
}
pub fn descending(field: Field) -> Self {
Sort {
field,
order: Order::Descending,
}
}
}
impl fmt::Display for Sort {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let order = match self.order {
Order::Ascending => "asc",
Order::Descending => "desc",
};
write!(f, "{order}({})", self.field)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Refine {
filters: Vec<Filter>,
sort: Option<Sort>,
}
impl Refine {
pub fn new() -> Self {
Refine::default()
}
pub fn filter(mut self, filter: Filter) -> Self {
self.filters.push(filter);
self
}
pub fn sort(mut self, sort: Sort) -> Self {
self.sort = Some(sort);
self
}
pub fn is_empty(&self) -> bool {
self.filters.is_empty() && self.sort.is_none()
}
pub(crate) fn params(&self) -> Vec<(&'static str, String)> {
let filters = self
.filters
.iter()
.map(|filter| ("filter", filter.to_string()));
let sort = self.sort.map(|sort| ("sort", sort.to_string()));
filters.chain(sort).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
const WIRE: &str = r#"{
"oci": "06024047477-06220256775",
"citing": "omid:br/06024047477 doi:10.22533/at.ed.9662430046",
"cited": "omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
"creation": "2024",
"timespan": "P2Y",
"journal_sc": "no",
"author_sc": "no"
}"#;
#[test]
fn a_citation_reads_every_stringly_typed_field() {
let citation: Citation = serde_json::from_str(WIRE).unwrap();
assert_eq!(citation.oci.to_string(), "06024047477-06220256775");
assert_eq!(citation.citing_doi(), Some("10.22533/at.ed.9662430046"));
assert_eq!(citation.cited_doi(), Some("10.1016/j.marpol.2021.104855"));
assert_eq!(citation.creation.unwrap().year(), 2024);
assert_eq!(citation.timespan.unwrap().as_months(), 24);
assert!(!citation.journal_self_citation);
assert!(!citation.author_self_citation);
assert_eq!(citation.cited.len(), 3);
}
#[test]
fn an_unknown_creation_or_timespan_is_none_rather_than_an_error() {
let wire = WIRE.replace(r#""creation": "2024""#, r#""creation": """#);
let wire = wire.replace(r#""timespan": "P2Y""#, r#""timespan": """#);
let citation: Citation = serde_json::from_str(&wire).unwrap();
assert_eq!(citation.creation, None);
assert_eq!(citation.timespan, None);
}
#[test]
fn a_self_citation_reads_as_the_boolean_it_is() {
let wire = WIRE.replace(r#""author_sc": "no""#, r#""author_sc": "yes""#);
let citation: Citation = serde_json::from_str(&wire).unwrap();
assert!(citation.author_self_citation);
}
#[test]
fn a_refinement_renders_the_parameters_the_api_reads() {
let refine = Refine::new()
.filter(Filter::greater_than(Field::Creation, "2023"))
.filter(Filter::is(Field::AuthorSelfCitation, "no"))
.sort(Sort::descending(Field::Timespan));
assert_eq!(
refine.params(),
vec![
("filter", "creation:>2023".to_string()),
("filter", "author_sc:no".to_string()),
("sort", "desc(timespan)".to_string()),
]
);
}
#[test]
fn an_empty_refinement_asks_for_nothing() {
assert!(Refine::new().is_empty());
assert!(Refine::new().params().is_empty());
}
}