bolt_web/
client.rs

1use serde::Serialize;
2use serde::de::DeserializeOwned;
3use std::collections::HashMap;
4
5#[derive(Clone)]
6pub struct Client {
7    client: reqwest::Client,
8}
9
10impl Client {
11    pub fn new() -> Self {
12        Self {
13            client: reqwest::Client::new(),
14        }
15    }
16
17    pub async fn get<U: DeserializeOwned>(
18        &self,
19        url: &str,
20        headers: Option<HashMap<&str, &str>>,
21    ) -> Result<U, reqwest::Error> {
22        let mut req = self.client.get(url);
23        if let Some(hdrs) = headers {
24            for (k, v) in hdrs {
25                req = req.header(k, v);
26            }
27        }
28        let resp = req.send().await?;
29        resp.json::<U>().await
30    }
31
32    pub async fn post<T: Serialize + ?Sized, U: DeserializeOwned>(
33        &self,
34        url: &str,
35        body: &T,
36        headers: Option<HashMap<&str, &str>>,
37    ) -> Result<U, reqwest::Error> {
38        let mut req = self.client.post(url).json(body);
39        if let Some(hdrs) = headers {
40            for (k, v) in hdrs {
41                req = req.header(k, v);
42            }
43        }
44        let resp = req.send().await?;
45        resp.json::<U>().await
46    }
47
48    pub async fn put<T: Serialize + ?Sized, U: DeserializeOwned>(
49        &self,
50        url: &str,
51        body: &T,
52        headers: Option<HashMap<&str, &str>>,
53    ) -> Result<U, reqwest::Error> {
54        let mut req = self.client.put(url).json(body);
55        if let Some(hdrs) = headers {
56            for (k, v) in hdrs {
57                req = req.header(k, v);
58            }
59        }
60        let resp = req.send().await?;
61        resp.json::<U>().await
62    }
63
64    pub async fn patch<T: Serialize + ?Sized, U: DeserializeOwned>(
65        &self,
66        url: &str,
67        body: &T,
68        headers: Option<HashMap<&str, &str>>,
69    ) -> Result<U, reqwest::Error> {
70        let mut req = self.client.patch(url).json(body);
71        if let Some(hdrs) = headers {
72            for (k, v) in hdrs {
73                req = req.header(k, v);
74            }
75        }
76        let resp = req.send().await?;
77        resp.json::<U>().await
78    }
79
80    pub async fn delete<U: DeserializeOwned>(
81        &self,
82        url: &str,
83        headers: Option<HashMap<&str, &str>>,
84    ) -> Result<U, reqwest::Error> {
85        let mut req = self.client.delete(url);
86        if let Some(hdrs) = headers {
87            for (k, v) in hdrs {
88                req = req.header(k, v);
89            }
90        }
91        let resp = req.send().await?;
92        resp.json::<U>().await
93    }
94}