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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use clients::{Client, HttpClient};
use constants::AUTH;
use errors::{UrlParseError, UrlParseResult};
use http::{Method, Request};
use serde::Deserialize;
use serde_json::Value;
use std::{fmt::Debug, pin::Pin, sync::Arc};
use tokio::sync::Mutex;
use url::Url;
use utils::check_uri;
pub use http::{Response, Uri};
pub use params::Paramable;
pub use request::Requestable;
pub use types::Result;
mod clients;
mod constants;
mod errors;
mod params;
mod request;
mod types;
mod utils;
#[derive(Debug)]
pub struct Firebase {
base_uri: Url,
client: Arc<Mutex<Client>>,
}
impl Firebase {
pub fn new(uri: &str) -> UrlParseResult<Self>
where
Self: Sized,
{
match check_uri(uri) {
Ok(uri) => Ok(Self {
base_uri: uri,
client: Arc::new(Mutex::new(Client::default())),
}),
Err(err) => Err(err),
}
}
pub fn auth(uri: &str, auth_key: &str) -> UrlParseResult<Self>
where
Self: Sized,
{
match check_uri(uri) {
Ok(mut uri) => {
uri.set_query(Some(&format!("{AUTH}={auth_key}")));
Ok(Self {
base_uri: uri,
client: Arc::new(Mutex::new(Client::default())),
})
}
Err(err) => Err(err),
}
}
pub fn base_uri(&self) -> String {
self.base_uri.to_string()
}
}
impl Firebase {
pub fn at(&self, path: &str) -> Self {
let re_path: String = self
.base_uri
.path_segments()
.unwrap_or_else(|| panic!("cannot be base"))
.map(|seg| format!("{}/", seg.trim_end_matches(".json")))
.collect();
let new_path = re_path + path;
let mut uri = self.base_uri.clone();
uri.set_path(&format!("{}.json", new_path.trim_end_matches(".json")));
Firebase {
base_uri: uri,
client: Arc::clone(&self.client),
}
}
}
impl Requestable for Firebase {
fn request<'life0, 'async_trait, Resp>(
&'life0 self,
method: Method,
data: Option<Value>,
) -> Pin<
Box<
dyn core::future::Future<Output = Result<Response<Resp>>>
+ core::marker::Send
+ 'async_trait,
>,
>
where
Resp: for<'a> Deserialize<'a>,
Resp: 'async_trait,
'life0: 'async_trait,
Self: 'async_trait,
{
Box::pin(async {
let req = Request::builder()
.method(method)
.uri(
self.base_uri
.to_string()
.parse::<Uri>()
.expect("infallible"),
)
.body(data)
.unwrap();
let client = self.client.lock().await;
(*client).send(req).await
})
}
}
impl Paramable for Firebase {
fn add_param<T>(&self, key: &str, value: T) -> Self
where
T: ToString,
{
let mut uri = self.base_uri.clone();
uri.query_pairs_mut().append_pair(key, &value.to_string());
Self {
base_uri: uri,
client: Arc::clone(&self.client),
}
}
}
#[cfg(test)]
mod tests {
use crate::{Firebase, UrlParseError};
const URI: &str = "https://firebase_id.firebaseio.com";
const URI_WITH_SLASH: &str = "https://firebase_id.firebaseio.com/";
const URI_NON_HTTPS: &str = "http://firebase_id.firebaseio.com/";
#[tokio::test]
async fn simple() {
let firebase = Firebase::new(URI).unwrap();
assert_eq!(URI_WITH_SLASH.to_string(), firebase.base_uri());
}
#[tokio::test]
async fn non_https() {
let firebase = Firebase::new(URI_NON_HTTPS).map_err(|e| e.to_string());
assert_eq!(
firebase.err(),
Some(String::from(UrlParseError::NotHttps.to_string()))
);
}
#[tokio::test]
async fn with_auth() {
let firebase = Firebase::auth(URI, "auth_key").unwrap();
assert_eq!(
format!("{}/?auth=auth_key", URI.to_string()),
firebase.base_uri()
);
}
}