Skip to main content

opencitations_client/
meta.rs

1//! OpenCitations Meta: the bibliographic record behind an identifier.
2//!
3//! Meta is flatter than crossref's work record and packs structure into
4//! strings -- the authors are one semicolon-joined list, and every name carries
5//! its identifiers in square brackets after it. The types here unpack that once
6//! so callers are not left splitting strings.
7
8use crate::date::PartialDate;
9use crate::id::Identifier;
10use serde::{Deserialize, Deserializer, Serialize};
11
12/// A bibliographic record, as OpenCitations Meta holds it.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Metadata {
15    /// every identifier this work is known by
16    #[serde(deserialize_with = "bag")]
17    pub id: Vec<Identifier>,
18    /// the title, absent where Meta holds none
19    #[serde(deserialize_with = "blank_is_none")]
20    pub title: Option<String>,
21    /// the authors, in the order they are credited
22    #[serde(deserialize_with = "entities")]
23    pub author: Vec<Entity>,
24    /// the editors, in the order they are credited
25    #[serde(default, deserialize_with = "entities")]
26    pub editor: Vec<Entity>,
27    /// when it was published, to whatever precision is recorded
28    #[serde(rename = "pub_date", deserialize_with = "blank_date_is_none")]
29    pub published: Option<PartialDate>,
30    /// the journal, book or proceedings it appeared in
31    #[serde(default, deserialize_with = "entity")]
32    pub venue: Option<Entity>,
33    /// the volume within the venue
34    #[serde(default, deserialize_with = "blank_is_none")]
35    pub volume: Option<String>,
36    /// the issue within the volume
37    #[serde(default, deserialize_with = "blank_is_none")]
38    pub issue: Option<String>,
39    /// the page or page range, e.g. `104855` or `31-40`
40    #[serde(default, deserialize_with = "blank_is_none")]
41    pub page: Option<String>,
42    /// what kind of work it is, e.g. `journal article`
43    #[serde(rename = "type", default, deserialize_with = "blank_is_none")]
44    pub type_: Option<String>,
45    /// who published it
46    #[serde(default, deserialize_with = "entity")]
47    pub publisher: Option<Entity>,
48}
49
50impl Metadata {
51    /// The work's DOI, when it has one.
52    pub fn doi(&self) -> Option<&str> {
53        self.id.iter().find_map(Identifier::as_doi)
54    }
55}
56
57/// Something Meta names and identifies: an author, an editor, a publisher or a
58/// venue.
59///
60/// All four arrive in the same shape -- a name, then the identifiers it is
61/// known by in square brackets -- which is why one type covers them.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct Entity {
64    /// the name as Meta writes it; `Family, Given` for a person
65    pub name: String,
66    /// every identifier it is known by, often just an `omid:`
67    pub ids: Vec<Identifier>,
68}
69
70impl Entity {
71    /// The family name, for an entity whose name is written `Family, Given`.
72    ///
73    /// [`None`] for a publisher or a venue, whose names carry no comma.
74    pub fn family(&self) -> Option<&str> {
75        self.name.split_once(',').map(|(family, _)| family.trim())
76    }
77
78    /// The given names, for an entity whose name is written `Family, Given`.
79    pub fn given(&self) -> Option<&str> {
80        self.name
81            .split_once(',')
82            .map(|(_, given)| given.trim())
83            .filter(|given| !given.is_empty())
84    }
85
86    /// Reads one `Name [id id]` entry.
87    ///
88    /// The brackets are optional: Meta writes a bare name for an entity it has
89    /// no identifier for.
90    fn parse(raw: &str) -> Result<Option<Self>, crate::Error> {
91        let raw = raw.trim();
92        if raw.is_empty() {
93            return Ok(None);
94        }
95
96        let (name, ids) = match raw.strip_suffix(']').and_then(|rest| rest.rsplit_once('[')) {
97            Some((name, ids)) => (name.trim(), Identifier::parse_bag(ids)?),
98            None => (raw, Vec::new()),
99        };
100
101        Ok(Some(Entity {
102            name: name.to_string(),
103            ids,
104        }))
105    }
106}
107
108/// Reads the space-separated bag of identifiers in the `id` field.
109fn bag<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Identifier>, D::Error> {
110    let raw = String::deserialize(deserializer)?;
111    Identifier::parse_bag(&raw).map_err(serde::de::Error::custom)
112}
113
114/// Reads a string field that is empty where Meta holds nothing.
115fn blank_is_none<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
116    let raw = String::deserialize(deserializer)?;
117    let raw = raw.trim();
118    Ok((!raw.is_empty()).then(|| raw.to_string()))
119}
120
121/// Reads the `pub_date`, which is empty where Meta holds no date.
122fn blank_date_is_none<'de, D: Deserializer<'de>>(
123    deserializer: D,
124) -> Result<Option<PartialDate>, D::Error> {
125    let raw = String::deserialize(deserializer)?;
126    let raw = raw.trim();
127    if raw.is_empty() {
128        return Ok(None);
129    }
130    raw.parse().map(Some).map_err(serde::de::Error::custom)
131}
132
133/// Reads the semicolon-joined list the `author` and `editor` fields hold.
134fn entities<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Entity>, D::Error> {
135    let raw = String::deserialize(deserializer)?;
136    raw.split(';')
137        .map(Entity::parse)
138        .collect::<Result<Vec<_>, _>>()
139        .map(|entities| entities.into_iter().flatten().collect())
140        .map_err(serde::de::Error::custom)
141}
142
143/// Reads the single entity the `venue` and `publisher` fields hold.
144fn entity<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Entity>, D::Error> {
145    let raw = String::deserialize(deserializer)?;
146    Entity::parse(&raw).map_err(serde::de::Error::custom)
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    /// The shape the api actually answers with, as captured from
154    /// `/meta/v1/metadata/doi:10.1016/j.marpol.2021.104855`.
155    const WIRE: &str = r#"{
156        "id": "doi:10.1016/j.marpol.2021.104855 openalex:W3214241825 omid:br/06220256775",
157        "title": "Sustainable Regional Industry Development Through Co-Evolution",
158        "author": "Lindfors, Emil Tomson [omid:ra/06220760311]; Jakobsen, Stig-Erik [omid:ra/06220760312]",
159        "pub_date": "2022-01",
160        "issue": "",
161        "volume": "135",
162        "venue": "Marine Policy [issn:0308-597X issn:1872-9460 omid:br/062607308]",
163        "type": "journal article",
164        "page": "104855",
165        "publisher": "Elsevier Bv [crossref:78 omid:ra/0610116009]",
166        "editor": ""
167    }"#;
168
169    #[test]
170    fn a_record_unpacks_the_strings_meta_packs_structure_into() {
171        let meta: Metadata = serde_json::from_str(WIRE).unwrap();
172
173        assert_eq!(meta.doi(), Some("10.1016/j.marpol.2021.104855"));
174        assert_eq!(meta.id.len(), 3);
175        assert_eq!(meta.published.unwrap().to_string(), "2022-01");
176        assert_eq!(meta.volume.as_deref(), Some("135"));
177        assert_eq!(meta.type_.as_deref(), Some("journal article"));
178    }
179
180    #[test]
181    fn the_authors_split_into_one_entity_each() {
182        let meta: Metadata = serde_json::from_str(WIRE).unwrap();
183
184        assert_eq!(meta.author.len(), 2);
185        assert_eq!(meta.author[0].family(), Some("Lindfors"));
186        assert_eq!(meta.author[0].given(), Some("Emil Tomson"));
187        assert_eq!(meta.author[0].ids, vec![Identifier::omid("ra/06220760311")]);
188        assert_eq!(meta.author[1].family(), Some("Jakobsen"));
189    }
190
191    #[test]
192    fn a_venue_and_a_publisher_keep_their_identifiers() {
193        let meta: Metadata = serde_json::from_str(WIRE).unwrap();
194
195        let venue = meta.venue.unwrap();
196        assert_eq!(venue.name, "Marine Policy");
197        assert!(venue.ids.contains(&Identifier::issn("0308-597X")));
198        // a venue name carries no comma, so it has no family half
199        assert_eq!(venue.family(), None);
200
201        let publisher = meta.publisher.unwrap();
202        assert_eq!(publisher.name, "Elsevier Bv");
203        assert_eq!(publisher.ids.len(), 2);
204    }
205
206    /// Meta writes an empty string where it holds nothing, for every field.
207    #[test]
208    fn an_empty_field_is_absent_rather_than_empty() {
209        let meta: Metadata = serde_json::from_str(WIRE).unwrap();
210
211        assert_eq!(meta.issue, None);
212        assert!(meta.editor.is_empty());
213    }
214
215    #[test]
216    fn an_entity_without_identifiers_is_still_an_entity() {
217        let wire = WIRE.replace(
218            r#""publisher": "Elsevier Bv [crossref:78 omid:ra/0610116009]""#,
219            r#""publisher": "Some Press""#,
220        );
221        let meta: Metadata = serde_json::from_str(&wire).unwrap();
222
223        let publisher = meta.publisher.unwrap();
224        assert_eq!(publisher.name, "Some Press");
225        assert!(publisher.ids.is_empty());
226    }
227}