1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use reqwest::{Response, header::{self, AUTHORIZATION}};
use serde::Serialize;
use super::Client;
use std::error;
use crate::user::UserTypes;
impl Client {
pub async fn get(&self, path: String) ->
Result<Response, Box<dyn error::Error>> {
match self.base_url.join(path.as_str()) {
Ok(request_url) => {
match reqwest::get(request_url).await {
Ok(response) => Ok(response),
Err(e) => Err(Box::new(e) as Box<dyn error::Error>)
}
},
Err(e) => Err(Box::new(e) as Box<dyn error::Error>)
}
}
pub async fn post<T: Serialize + Sized>(
&self,
path: String,
body: &T
) -> Result<Response, Box<dyn error::Error>>
{
match self.base_url.join(path.as_str()) {
Ok(request_url) => {
let req_client = reqwest::Client::new();
let req = req_client
.post(request_url)
.header(header::CONTENT_TYPE, "application/json")
.body(serde_json::to_string(body).unwrap());
let authed_req = match &self.user {
Some(user) => {
match &user.usertype {
UserTypes::User => {
req.header(
AUTHORIZATION,
format!("User {}", user.token)
)
},
UserTypes::Admin => {
req.header(
AUTHORIZATION,
format!("Admin {}", user.token)
)
}
}
}
None => req
};
match authed_req.send().await {
Ok(response) => Ok(response),
Err(e) => Err(Box::new(e) as Box<dyn error::Error>)
}
},
Err(e) => Err(Box::new(e) as Box<dyn error::Error>)
}
}
pub async fn patch<T: Serialize + Sized>(
&self,
path: String,
body: &T
) -> Result<Response, Box<dyn error::Error>> {
match self.base_url.join(path.as_str()) {
Ok(request_url) => {
let req_client = reqwest::Client::new();
let req = req_client
.patch(request_url)
.header(header::CONTENT_TYPE, "application/json")
.body(serde_json::to_string(body).unwrap());
match req.send().await {
Ok(response) => Ok(response),
Err(e) => Err(Box::new(e) as Box<dyn error::Error>)
}
},
Err(e) => Err(Box::new(e) as Box<dyn error::Error>)
}
}
}