openlibrary_rs/
authors.rs

1use derive_builder::Builder;
2
3use crate::OpenlibraryRequest;
4
5#[derive(Default, Clone, Debug)]
6pub enum AuthorsType {
7    #[default]
8    Data,
9    Works,
10}
11
12/// The struct representation of a request to the [Authors API](https://openlibrary.org/dev/docs/api/authors)
13///
14/// The fields of this struct are private. If you want to view available fields that can be set please look at the [`AuthorsBuilder`] struct.
15#[derive(Builder, Default, Debug)]
16#[builder(setter(into), default)]
17pub struct Authors {
18    id: String,
19    authors_type: AuthorsType,
20    #[builder(default = "10")]
21    limit: u32,
22    offset: u32,
23}
24
25impl OpenlibraryRequest for Authors {
26    fn path(&self) -> String {
27        match self.authors_type {
28            AuthorsType::Data => format!("/authors/{}.json", self.id),
29            AuthorsType::Works => format!("/authors/{}/works.json", self.id),
30        }
31    }
32
33    fn query(&self) -> Vec<(&'static str, String)> {
34        vec![
35            ("limit", self.limit.to_string()),
36            ("offset", self.offset.to_string()),
37        ]
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use mockito::{mock, Matcher};
44    use serde_json::json;
45
46    use crate::OpenlibraryRequest;
47
48    use super::AuthorsBuilder;
49
50    #[test]
51    fn test_authors_execute() {
52        let authors = AuthorsBuilder::default().id("OL23919A").build().unwrap();
53
54        let json = json!({
55            "key": "authors/OL23919A",
56            "name": "J. K. Rowling",
57            "entity_type": "person",
58        });
59
60        let _m = mock(
61            "GET",
62            Matcher::Regex(format!(r"{}\w*", authors.url().path())),
63        )
64        .with_header("content-type", "application/json")
65        .with_body(json.to_string())
66        .create();
67
68        let result = authors.execute();
69
70        assert_eq!(result["key"], "authors/OL23919A");
71        assert_eq!(result["name"], "J. K. Rowling");
72        assert_eq!(result["entity_type"], "person");
73    }
74}