discogs_api/client/
client.rs

1use super::{Auth, ClientBuilder};
2use crate::{endpoints::Endpoint, Error, ParsedResponse};
3use reqwest::Url;
4use serde::Deserialize;
5
6pub struct Client {
7    pub(super) client: reqwest::blocking::Client,
8    pub(super) auth: Option<Auth>,
9    pub(super) url_base: Url,
10}
11
12impl Client {
13    #[must_use]
14    #[inline]
15    pub fn builder() -> ClientBuilder {
16        ClientBuilder::new()
17    }
18
19    #[inline]
20    pub fn get<'de, E: Endpoint<'de>>(
21        &self,
22        params: E::Parameters,
23    ) -> Result<ParsedResponse<E::ReturnType>, Error> {
24        self.get_custom_return_type::<E, E::ReturnType>(params)
25    }
26
27    /// This method is here to allow users of this library
28    /// to change the type the response is parsed as.
29    ///
30    /// Use `Client::get` where possible to use the regular types.<br/>
31    /// Use [`serde_json::Value`] as `R` to parse any valid response.
32    #[inline]
33    pub fn get_custom_return_type<'a, 'b, E: Endpoint<'a>, R: Deserialize<'b>>(
34        &self,
35        params: E::Parameters,
36    ) -> Result<ParsedResponse<R>, Error> {
37        E::build_url(&self.url_base, params).and_then(|url| self.get_url(url))
38    }
39
40    /// This method only modifies the given url in that it will add the user token if applicable
41    pub fn get_url<'de, R>(&self, mut url: Url) -> Result<ParsedResponse<R>, Error>
42    where
43        R: Deserialize<'de>,
44    {
45        if let Some(Auth::Token(token)) = &self.auth {
46            url.query_pairs_mut().append_pair("token", token);
47        }
48
49        self.client
50            .get(url)
51            .send()
52            .map_err(Error::NetError)
53            .and_then(ParsedResponse::new)
54    }
55}
56
57impl Default for Client {
58    /// Can panic. If failable, build manually.
59    #[must_use]
60    fn default() -> Self {
61        Self::builder().build().unwrap()
62    }
63}