Skip to main content

open_library_api_rs/api/
query.rs

1// v0.0.1
2use std::collections::HashMap;
3
4use crate::client::OpenLibraryClient;
5use crate::error::{Error, Result};
6use crate::models::query::QueryResponse;
7use crate::validation::validate_limit;
8
9impl OpenLibraryClient {
10    /// Execute a generic query against the `/query.json` endpoint.
11    ///
12    /// `type_` must be one of `/type/edition`, `/type/work`, `/type/author`, etc.
13    /// `fields` is a map of field name → value to filter on.
14    /// `limit` controls the number of results (max 1000).
15    pub async fn query(
16        &self,
17        type_: &str,
18        fields: &HashMap<String, String>,
19        limit: u32,
20        offset: u32,
21    ) -> Result<QueryResponse> {
22        if type_.is_empty() {
23            return Err(Error::InvalidInput("query type must not be empty".into()));
24        }
25        validate_limit(limit)?;
26
27        let mut url = self.base_url.join("query.json")?;
28        {
29            let mut qp = url.query_pairs_mut();
30            qp.append_pair("type", type_);
31            qp.append_pair("limit", &limit.to_string());
32            qp.append_pair("offset", &offset.to_string());
33            for (k, v) in fields {
34                qp.append_pair(k, v);
35            }
36        }
37        self.get_json(url).await
38    }
39}