-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.rs
More file actions
81 lines (71 loc) · 2.14 KB
/
client.rs
File metadata and controls
81 lines (71 loc) · 2.14 KB
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
use ureq::typestate::{WithBody, WithoutBody};
use crate::default_root;
#[derive(Debug)]
pub struct Client {
company: Option<String>,
role: Option<String>,
root: url::Url,
token: String,
}
/// Getters & instantiation
impl Client {
pub fn new(token: String) -> Self {
Self { company: None, role: None, root: default_root(), token }
}
pub fn role(&self) -> Option<&String> {
self.role.as_ref()
}
pub fn company(&self) -> Option<&String> {
self.company.as_ref()
}
pub fn with_company_and_role(&self, company: String, role: String) -> Self {
Self {
company: Some(company),
role: Some(role),
root: self.root.clone(),
token: self.token.clone(),
}
}
/// Used for testing mainly
#[allow(dead_code)]
pub(crate) fn with_root(&self, root: url::Url) -> Self {
Self {
company: self.company.clone(),
role: self.role.clone(),
root,
token: self.token.clone(),
}
}
}
/// Methods for internal use
impl Client {
fn agent(&self) -> ureq::Agent {
ureq::agent()
}
pub(super) fn get(&self, path: &str) -> ureq::RequestBuilder<WithoutBody> {
let mut request = self
.agent()
.get(self.root.join(path).unwrap().as_str())
.header("Authorization", &format!("Bearer {}", self.token));
if let Some(company) = &self.company {
request = request.header("Company", company);
}
if let Some(role) = &self.role {
request = request.header("Role", role);
}
request
}
pub(super) fn post(&self, path: &str) -> ureq::RequestBuilder<WithBody> {
let mut request = self
.agent()
.post(self.root.join(path).unwrap().as_str())
.header("Authorization", &format!("Bearer {}", self.token));
if let Some(company) = &self.company {
request = request.header("Company", company);
}
if let Some(role) = &self.role {
request = request.header("Role", role);
}
request
}
}