nadeo_api/request/
request_builder.rs

1use crate::auth::AuthType;
2use crate::request::NadeoRequest;
3use crate::{Error, Result};
4use reqwest::header::{HeaderMap, IntoHeaderName};
5use reqwest::Method;
6use serde::{Deserialize, Serialize};
7
8/// Used for creating [`NadeoRequest`]s.
9/// `URL`, [`Method`] and [`AuthType`] must be provided.
10///
11/// [`NadeoRequest`]: NadeoRequest
12/// [`Method`]: Method
13/// [`AuthType`]: AuthType
14#[derive(Default)]
15pub struct NadeoRequestBuilder {
16    auth_type: Option<AuthType>,
17    url: Option<String>,
18    method: Option<Method>,
19    headers: HeaderMap,
20    body: Option<String>,
21}
22
23/// Error when the Request is invalid. For example if a required field is missing.
24#[derive(thiserror::Error, Debug, Serialize, Deserialize)]
25pub enum RequestBuilderError {
26    #[error("no URL was provided")]
27    MissingUrl,
28    #[error("no HTTP method was provided")]
29    MissingHttpMethod,
30    #[error("no AuthType was provided")]
31    MissingAuthType,
32}
33
34impl NadeoRequestBuilder {
35    /// Adds a text body to the request. Usually JSON.
36    pub fn body(mut self, json: &str) -> Self {
37        self.body = Some(json.to_string());
38
39        self
40    }
41
42    pub fn url(mut self, url: &str) -> Self {
43        self.url = Some(url.to_string());
44
45        self
46    }
47
48    pub fn method(mut self, method: Method) -> Self {
49        self.method = Some(method);
50
51        self
52    }
53
54    pub fn auth_type(mut self, auth_type: AuthType) -> Self {
55        self.auth_type = Some(auth_type);
56
57        self
58    }
59
60    /// Adds a header to the request. Adding a header should not be required in most cases.
61    ///
62    /// # Panics
63    ///
64    /// Panics if there is an error parsing the value.
65    pub fn add_header<K>(mut self, key: K, val: &str) -> Self
66    where
67        K: IntoHeaderName,
68    {
69        self.headers.insert(key, val.parse().unwrap());
70        self
71    }
72
73    /// Converts the `NadeoRequestBuilder` into a [`NadeoRequest`].
74    /// `URL`, [`Method`] and [`AuthType`] are required.
75    ///
76    /// [`NadeoRequest`]: NadeoRequest
77    /// [`Method`]: Method
78    /// [`AuthType`]: AuthType
79    pub fn build(self) -> Result<NadeoRequest> {
80        if self.url.is_none() {
81            return Err(Error::from(RequestBuilderError::MissingUrl));
82        }
83        if self.method.is_none() {
84            return Err(Error::from(RequestBuilderError::MissingHttpMethod));
85        }
86        if self.auth_type.is_none() {
87            return Err(Error::from(RequestBuilderError::MissingAuthType));
88        }
89
90        Ok(NadeoRequest {
91            auth_type: self.auth_type.unwrap(),
92            method: self.method.unwrap(),
93            url: self.url.unwrap(),
94            headers: self.headers,
95            body: self.body,
96        })
97    }
98}