septoria/
data_client.rs

1use crate::api::Requests;
2use crate::error::Error;
3use reqwest::Url;
4use serde::de::DeserializeOwned;
5use serde::Serialize;
6use std::fmt::Debug;
7
8use crate::util::build_reqwest_client;
9
10static DATA_ENDPOINT: &str = "https://data.lemon.markets/v1/";
11
12#[derive(Debug)]
13/// The data client for the Lemon API.
14pub struct DataClient {
15    /// The API key.
16    pub api_key: String,
17    /// The base url for the API
18    pub base_url: Url,
19    /// Internal client used for all requests.
20    pub(crate) client: reqwest::blocking::Client,
21}
22
23impl DataClient {
24    /// Create a new data client.
25    pub fn new(api_key: String) -> Self {
26        let client = build_reqwest_client(&api_key);
27        Self {
28            api_key,
29            base_url: Url::parse(DATA_ENDPOINT).unwrap(),
30            client,
31        }
32    }
33}
34
35impl Requests for DataClient {
36    /// Generic get request
37    fn get<T: DeserializeOwned + Debug>(&self, path: &str) -> Result<T, Error> {
38        let url = format!("{}/{}", self.base_url, path);
39        let r = self.client.get(&url).send()?;
40        let json = self.response_handler(r)?;
41        Ok(json)
42    }
43    /// Generic get request with query parameters
44    fn get_with_query<T: DeserializeOwned + Debug, Q: IntoIterator + Serialize>(
45        &self,
46        path: &str,
47        query: Q,
48    ) -> Result<T, Error> {
49        let url = format!("{}/{}", self.base_url, path);
50        let r = self.client.get(&url).query(&query).send()?;
51        let json = self.response_handler(r)?;
52        dbg!(&json);
53        Ok(json)
54    }
55    /// Generic post request
56    fn post<T: DeserializeOwned, B: Serialize>(&self, path: &str, body: B) -> Result<T, Error> {
57        let url = format!("{}/{}", self.base_url, path);
58        let body_string = serde_json::to_string(&body)?;
59        let r = self.client.post(&url).body(body_string).send()?;
60        let json = self.response_handler(r)?;
61        Ok(json)
62    }
63    /// Generic delete request
64    fn delete<T: DeserializeOwned>(&self, path: &str, path_param: &str) -> Result<T, Error> {
65        let url = format!("{}/{}/{}", self.base_url, path, path_param);
66        let r = self.client.delete(&url).send()?;
67        let json = self.response_handler::<T>(r)?;
68        Ok(json)
69    }
70}