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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use error;
use method;
use native_client;
use path::Path;
use request_information;
use std::cell;
use std::fmt;
use std::rc;
#[derive(Debug)]
pub struct Domain {
client: rc::Rc<cell::RefCell<native_client::NativeClient>>,
info: rc::Rc<cell::RefCell<request_information::RequestInformation>>,
}
impl Domain {
pub fn new(domain: &str) -> Self {
let domain = domain.to_string();
let client = rc::Rc::new(cell::RefCell::new(native_client::NativeClient::new()));
let info =
rc::Rc::new(cell::RefCell::new(request_information::RequestInformation::new(domain)));
Domain {
client,
info,
}
}
pub fn query(
&mut self,
key: &str,
value: &impl fmt::Display,
) -> Result<(), error::Error> {
self.info.borrow_mut().add_query_param(key, value)?;
Ok(())
}
pub fn header(
&mut self,
key: &'static str,
value: &impl fmt::Display,
) {
self.info.borrow_mut().add_header(key, value);
}
pub fn get(&self) -> Path {
self.method(method::Method::Get)
}
pub fn post(&self) -> Path {
self.method(method::Method::Post)
}
pub fn put(&self) -> Path {
self.method(method::Method::Put)
}
pub fn delete(&self) -> Path {
self.method(method::Method::Delete)
}
pub fn patch(&self) -> Path {
self.method(method::Method::Patch)
}
pub fn head(&self) -> Path {
self.method(method::Method::Head)
}
pub fn options(&self) -> Path {
self.method(method::Method::Options)
}
pub fn connect(&self) -> Path {
self.method(method::Method::Connect)
}
pub fn trace(&self) -> Path {
self.method(method::Method::Trace)
}
pub fn method(
&self,
method: method::Method,
) -> Path {
Path::new(method, rc::Rc::clone(&self.client), rc::Rc::clone(&self.info))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn domain_no_end_slash() {
let domain = Domain::new("https://api.example.com").get();
assert_eq!(domain.to_string(), "https://api.example.com");
}
#[test]
fn domain_should_strip_slash() {
let domain = Domain::new("https://api.example.com/").get();
assert_eq!(domain.to_string(), "https://api.example.com");
}
#[test]
fn domain_with_base_query() {
let mut domain = Domain::new("https://api.example.com/");
domain.query(&"type", &"donkeys");
let path = domain.get().push(&"list");
assert_eq!(path.to_string(), "https://api.example.com/list?type=donkeys");
}
#[test]
fn domain_with_base_query_and_path() {
let mut domain = Domain::new("https://api.example.com/");
domain.query(&"type", &"donkeys");
let path = domain.get().push(&"list").query(&"length", &"long");
assert_eq!(path.to_string(), "https://api.example.com/list?type=donkeys&length=long");
}
}