opencitations-client 0.1.0

An async Rust client for the OpenCitations Index and Meta REST APIs
Documentation
//! OpenCitations Meta: the bibliographic record behind an identifier.
//!
//! Meta is flatter than crossref's work record and packs structure into
//! strings -- the authors are one semicolon-joined list, and every name carries
//! its identifiers in square brackets after it. The types here unpack that once
//! so callers are not left splitting strings.

use crate::date::PartialDate;
use crate::id::Identifier;
use serde::{Deserialize, Deserializer, Serialize};

/// A bibliographic record, as OpenCitations Meta holds it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Metadata {
    /// every identifier this work is known by
    #[serde(deserialize_with = "bag")]
    pub id: Vec<Identifier>,
    /// the title, absent where Meta holds none
    #[serde(deserialize_with = "blank_is_none")]
    pub title: Option<String>,
    /// the authors, in the order they are credited
    #[serde(deserialize_with = "entities")]
    pub author: Vec<Entity>,
    /// the editors, in the order they are credited
    #[serde(default, deserialize_with = "entities")]
    pub editor: Vec<Entity>,
    /// when it was published, to whatever precision is recorded
    #[serde(rename = "pub_date", deserialize_with = "blank_date_is_none")]
    pub published: Option<PartialDate>,
    /// the journal, book or proceedings it appeared in
    #[serde(default, deserialize_with = "entity")]
    pub venue: Option<Entity>,
    /// the volume within the venue
    #[serde(default, deserialize_with = "blank_is_none")]
    pub volume: Option<String>,
    /// the issue within the volume
    #[serde(default, deserialize_with = "blank_is_none")]
    pub issue: Option<String>,
    /// the page or page range, e.g. `104855` or `31-40`
    #[serde(default, deserialize_with = "blank_is_none")]
    pub page: Option<String>,
    /// what kind of work it is, e.g. `journal article`
    #[serde(rename = "type", default, deserialize_with = "blank_is_none")]
    pub type_: Option<String>,
    /// who published it
    #[serde(default, deserialize_with = "entity")]
    pub publisher: Option<Entity>,
}

impl Metadata {
    /// The work's DOI, when it has one.
    pub fn doi(&self) -> Option<&str> {
        self.id.iter().find_map(Identifier::as_doi)
    }
}

/// Something Meta names and identifies: an author, an editor, a publisher or a
/// venue.
///
/// All four arrive in the same shape -- a name, then the identifiers it is
/// known by in square brackets -- which is why one type covers them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entity {
    /// the name as Meta writes it; `Family, Given` for a person
    pub name: String,
    /// every identifier it is known by, often just an `omid:`
    pub ids: Vec<Identifier>,
}

impl Entity {
    /// The family name, for an entity whose name is written `Family, Given`.
    ///
    /// [`None`] for a publisher or a venue, whose names carry no comma.
    pub fn family(&self) -> Option<&str> {
        self.name.split_once(',').map(|(family, _)| family.trim())
    }

    /// The given names, for an entity whose name is written `Family, Given`.
    pub fn given(&self) -> Option<&str> {
        self.name
            .split_once(',')
            .map(|(_, given)| given.trim())
            .filter(|given| !given.is_empty())
    }

    /// Reads one `Name [id id]` entry.
    ///
    /// The brackets are optional: Meta writes a bare name for an entity it has
    /// no identifier for.
    fn parse(raw: &str) -> Result<Option<Self>, crate::Error> {
        let raw = raw.trim();
        if raw.is_empty() {
            return Ok(None);
        }

        let (name, ids) = match raw.strip_suffix(']').and_then(|rest| rest.rsplit_once('[')) {
            Some((name, ids)) => (name.trim(), Identifier::parse_bag(ids)?),
            None => (raw, Vec::new()),
        };

        Ok(Some(Entity {
            name: name.to_string(),
            ids,
        }))
    }
}

/// Reads the space-separated bag of identifiers in the `id` field.
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)
}

/// Reads a string field that is empty where Meta holds nothing.
fn blank_is_none<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
    let raw = String::deserialize(deserializer)?;
    let raw = raw.trim();
    Ok((!raw.is_empty()).then(|| raw.to_string()))
}

/// Reads the `pub_date`, which is empty where Meta holds no date.
fn blank_date_is_none<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<PartialDate>, D::Error> {
    let raw = String::deserialize(deserializer)?;
    let raw = raw.trim();
    if raw.is_empty() {
        return Ok(None);
    }
    raw.parse().map(Some).map_err(serde::de::Error::custom)
}

/// Reads the semicolon-joined list the `author` and `editor` fields hold.
fn entities<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Entity>, D::Error> {
    let raw = String::deserialize(deserializer)?;
    raw.split(';')
        .map(Entity::parse)
        .collect::<Result<Vec<_>, _>>()
        .map(|entities| entities.into_iter().flatten().collect())
        .map_err(serde::de::Error::custom)
}

/// Reads the single entity the `venue` and `publisher` fields hold.
fn entity<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Entity>, D::Error> {
    let raw = String::deserialize(deserializer)?;
    Entity::parse(&raw).map_err(serde::de::Error::custom)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The shape the api actually answers with, as captured from
    /// `/meta/v1/metadata/doi:10.1016/j.marpol.2021.104855`.
    const WIRE: &str = r#"{
        "id": "doi:10.1016/j.marpol.2021.104855 openalex:W3214241825 omid:br/06220256775",
        "title": "Sustainable Regional Industry Development Through Co-Evolution",
        "author": "Lindfors, Emil Tomson [omid:ra/06220760311]; Jakobsen, Stig-Erik [omid:ra/06220760312]",
        "pub_date": "2022-01",
        "issue": "",
        "volume": "135",
        "venue": "Marine Policy [issn:0308-597X issn:1872-9460 omid:br/062607308]",
        "type": "journal article",
        "page": "104855",
        "publisher": "Elsevier Bv [crossref:78 omid:ra/0610116009]",
        "editor": ""
    }"#;

    #[test]
    fn a_record_unpacks_the_strings_meta_packs_structure_into() {
        let meta: Metadata = serde_json::from_str(WIRE).unwrap();

        assert_eq!(meta.doi(), Some("10.1016/j.marpol.2021.104855"));
        assert_eq!(meta.id.len(), 3);
        assert_eq!(meta.published.unwrap().to_string(), "2022-01");
        assert_eq!(meta.volume.as_deref(), Some("135"));
        assert_eq!(meta.type_.as_deref(), Some("journal article"));
    }

    #[test]
    fn the_authors_split_into_one_entity_each() {
        let meta: Metadata = serde_json::from_str(WIRE).unwrap();

        assert_eq!(meta.author.len(), 2);
        assert_eq!(meta.author[0].family(), Some("Lindfors"));
        assert_eq!(meta.author[0].given(), Some("Emil Tomson"));
        assert_eq!(meta.author[0].ids, vec![Identifier::omid("ra/06220760311")]);
        assert_eq!(meta.author[1].family(), Some("Jakobsen"));
    }

    #[test]
    fn a_venue_and_a_publisher_keep_their_identifiers() {
        let meta: Metadata = serde_json::from_str(WIRE).unwrap();

        let venue = meta.venue.unwrap();
        assert_eq!(venue.name, "Marine Policy");
        assert!(venue.ids.contains(&Identifier::issn("0308-597X")));
        // a venue name carries no comma, so it has no family half
        assert_eq!(venue.family(), None);

        let publisher = meta.publisher.unwrap();
        assert_eq!(publisher.name, "Elsevier Bv");
        assert_eq!(publisher.ids.len(), 2);
    }

    /// Meta writes an empty string where it holds nothing, for every field.
    #[test]
    fn an_empty_field_is_absent_rather_than_empty() {
        let meta: Metadata = serde_json::from_str(WIRE).unwrap();

        assert_eq!(meta.issue, None);
        assert!(meta.editor.is_empty());
    }

    #[test]
    fn an_entity_without_identifiers_is_still_an_entity() {
        let wire = WIRE.replace(
            r#""publisher": "Elsevier Bv [crossref:78 omid:ra/0610116009]""#,
            r#""publisher": "Some Press""#,
        );
        let meta: Metadata = serde_json::from_str(&wire).unwrap();

        let publisher = meta.publisher.unwrap();
        assert_eq!(publisher.name, "Some Press");
        assert!(publisher.ids.is_empty());
    }
}