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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use reqwest::{Error, StatusCode};
use std::string::ToString;
use yesser_todo_db::Task;
pub struct Client {
pub hostname: String,
pub port: String,
client: reqwest::Client,
}
impl Client {
/// Creates a new `Client` for the given hostname.
///
/// If `port` is `None`, the client will use the default port `"6982"`.
///
/// # Examples
///
/// ```
/// let c = Client::new("http://127.0.0.1".to_string(), None);
/// assert_eq!(c.hostname, "http://127.0.0.1");
/// assert_eq!(c.port, "6982");
/// ```
pub fn new(hostname: String, port: Option<String>) -> Client {
match port {
None => {Client{hostname, port: "6982".to_string(), client: reqwest::Client::new(), }}
Some(port) => {Client{hostname, port, client: reqwest::Client::new(), }}
}
}
/// Fetches all tasks from the configured server.
///
/// # Returns
///
/// `(StatusCode, Vec<Task>)` where the `StatusCode` is the HTTP response status and the `Vec<Task>` is the list of tasks parsed from the response body.
///
/// # Examples
///
/// ```no_run
/// use api::Client;
/// use reqwest::StatusCode;
///
/// let client = Client::new("http://127.0.0.1".into(), None);
/// let rt = tokio::runtime::Runtime::new().unwrap();
/// let (status, tasks) = rt.block_on(client.get()).unwrap();
/// assert!(status == StatusCode::OK || status.is_success());
/// // `tasks` is a Vec<yesser_todo_db::Task>
/// ```
pub async fn get(&self) -> Result<(StatusCode, Vec<Task>), Error> {
let result = self.client
.get(format!("{}:{}/tasks", self.hostname, self.port).as_str())
.send().await;
match result {
Ok(result) => {
let status_code = result.status();
let result = result.json::<Vec<Task>>().await;
match result {
Ok(result) => {Ok((status_code, result))},
Err(err) => {Err(err)}
}
}
Err(err) => {Err(err)}
}
}
/// Adds a new task with the given name to the to-do service.
///
/// Sends the task name as JSON to the service's `/add` endpoint and returns the HTTP status
/// together with the created `Task` parsed from the response.
///
/// # Parameters
///
/// - `task_name`: The name of the task to create.
///
/// # Returns
///
/// A `(StatusCode, Task)` tuple containing the HTTP response status and the created `Task`.
///
/// # Examples
///
/// ```
/// # use yesser_todo_api::Client;
/// # use reqwest::StatusCode;
/// # #[tokio::test]
/// # async fn example_add() {
/// let client = Client::new("http://127.0.0.1".to_string(), None);
/// let (status, task) = client.add(&"example task".to_string()).await.unwrap();
/// assert_eq!(status, StatusCode::OK);
/// assert_eq!(task.name, "example task");
/// # }
/// ```
pub async fn add(&self, task_name: &String) -> Result<(StatusCode, Task), Error> {
let result = self.client
.post(format!("{}:{}/add", self.hostname, self.port).as_str())
.json(&task_name)
.send().await;
match result {
Ok(result) => {
let status_code = result.status();
let result = result.json::<Task>().await;
match result {
Ok(result) => {Ok((status_code, result))},
Err(err) => {Err(err)}
}
}
Err(err) => {Err(err)}
}
}
/// Retrieve the index of a task by name from the server.
///
/// Sends the task name as JSON to the server's `/index` endpoint and returns the HTTP status together with the parsed index on success.
///
/// # Parameters
///
/// - `task_name`: the name of the task to locate.
///
/// # Returns
///
/// `(StatusCode, usize)` where `usize` is the index of the task returned by the server, and `StatusCode` is the HTTP response status.
///
/// # Examples
///
/// ```no_run
/// use yesser_todo_api::Client;
/// use std::string::String;
///
/// # async fn run_example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("http://127.0.0.1".into(), None);
/// let (status, index) = client.get_index(&"example-task".into()).await?;
/// println!("status: {}, index: {}", status, index);
/// # Ok(()) }
/// ```
pub async fn get_index(&self, task_name: &String) -> Result<(StatusCode, usize), Error> {
let result = self.client
.get(format!("{}:{}/index", self.hostname, self.port).as_str())
.json(&task_name)
.send().await;
match result {
Ok(result) => {
let status_code = result.status();
let result = result.json::<usize>().await;
match result {
Ok(result) => Ok((status_code, result)),
Err(err) => {Err(err)}
}
}
Err(err) => {Err(err)}
}
}
/// Remove a task identified by name from the remote server.
///
/// This resolves the task's index on the server and requests deletion of that index.
/// If the index lookup returns a non-OK HTTP status, that status is returned unchanged.
/// Network or request errors are propagated as `Err`.
///
/// # Returns
///
/// `Ok(StatusCode)` containing the server's status for the delete request, or the non-OK
/// status returned by the index lookup; `Err(Error)` on request/transport failures.
///
/// # Examples
///
/// ```
/// # use yesser_todo_api::Client;
/// # use tokio;
/// #[tokio::main]
/// async fn main() {
/// let client = Client::new("http://127.0.0.1".to_string(), None);
/// let status = client.remove(&"example-task".to_string()).await;
/// // handle result...
/// let _ = status;
/// }
/// ```
pub async fn remove(&self, task_name: &String) -> Result<StatusCode, Error> {
let index_result = self.get_index(task_name).await;
let index: usize;
match index_result {
Ok((status_code, result)) => {
if status_code != StatusCode::OK {
return Ok(status_code);
}
index = result;
}
Err(err) => {return Err(err)}
}
let result = self.client
.delete(format!("{}:{}/remove", self.hostname, self.port).as_str())
.json(&index)
.send().await;
match result {
Ok(result) => {
Ok(result.status())
}
Err(err) => {Err(err)}
}
}
/// Marks the task with the given name as done and returns the HTTP status and the updated task.
///
/// If retrieving the task index returns a non-OK status, the function returns that status along with a `Task` whose `name` is `"Something went wrong"` and `done` is `false`.
///
/// # Returns
///
/// `(StatusCode, Task)` containing the response status and the task as returned by the server.
///
/// # Examples
///
/// ```
/// # use yesser_todo_db::Task;
/// # use reqwest::StatusCode;
/// # async fn _example() {
/// let client = crate::Client::new("http://127.0.0.1".to_string(), None);
/// let res = client.done(&"test".to_string()).await;
/// match res {
/// Ok((status, task)) => {
/// assert!(status == StatusCode::OK || status.is_client_error() || status.is_server_error());
/// // `task` is the updated task from the server
/// let _ = task.name;
/// }
/// Err(e) => panic!("request failed: {:?}", e),
/// }
/// # }
/// ```
pub async fn done(&self, task_name: &String) -> Result<(StatusCode, Task), Error> {
let index_result = self.get_index(task_name).await;
let index: usize;
match index_result {
Ok((status_code, result)) => {
if status_code != StatusCode::OK {
return Ok((status_code, Task{name: "Something went wrong".to_string(), done: false}));
}
index = result;
}
Err(err) => {return Err(err)}
}
let result = self.client
.post(format!("{}:{}/done", self.hostname, self.port).as_str())
.json(&index)
.send().await;
match result {
Ok(result) => {
let status_code = result.status();
match result.json::<Task>().await {
Ok(result) => Ok((status_code, result)),
Err(err) => {Err(err)}
}
}
Err(err) => {Err(err)}
}
}
/// Mark the task identified by `task_name` as not done and return the updated task with the response status.
///
/// Attempts to resolve the task's index by name; if index resolution returns a non-OK status, returns that status
/// together with a placeholder `Task` having name `"Something went wrong"` and `done: false`.
///
/// # Returns
///
/// `(StatusCode, Task)` with the HTTP response status and the updated task on success; if index lookup returns a non-OK status,
/// returns that status paired with a placeholder `Task`.
///
/// # Examples
///
/// ```
/// use yesser_todo_api::Client;
/// use std::string::String;
/// use reqwest::StatusCode;
///
/// let client = Client::new("http://127.0.0.1".to_string(), None);
/// let rt = tokio::runtime::Runtime::new().unwrap();
/// let res = rt.block_on(async { client.undone(&"example".to_string()).await }).unwrap();
/// assert!(matches!(res.0, StatusCode::OK) || res.0.is_client_error() || res.0.is_server_error());
/// ```
pub async fn undone(&self, task_name: &String) -> Result<(StatusCode, Task), Error> {
let index_result = self.get_index(task_name).await;
let index: usize;
match index_result {
Ok((status_code, result)) => {
if status_code != StatusCode::OK {
return Ok((status_code, Task{name: "Something went wrong".to_string(), done: false}));
}
index = result;
}
Err(err) => {return Err(err)}
}
let result = self.client
.post(format!("{}:{}/undone", self.hostname, self.port).as_str())
.json(&index)
.send().await;
match result {
Ok(result) => {
let status_code = result.status();
match result.json::<Task>().await {
Ok(result) => Ok((status_code, result)),
Err(err) => {Err(err)}
}
}
Err(err) => {Err(err)}
}
}
/// Clears all tasks on the remote to-do service.
///
/// Sends a DELETE request to the configured `/clear` endpoint and returns the HTTP status code.
///
/// # Examples
///
/// ```
/// # async fn example() {
/// let client = Client::new("http://127.0.0.1".to_string(), None);
/// let status = client.clear().await.unwrap();
/// assert_eq!(status, reqwest::StatusCode::OK);
/// # }
/// ```
pub async fn clear(&self) -> Result<StatusCode, Error> {
let result = self.client
.delete(format!("{}:{}/clear", self.hostname, self.port).as_str())
.send().await;
match result {
Ok(result) => Ok(result.status()),
Err(err) => {Err(err)}
}
}
/// Deletes all tasks marked as done on the remote to-do service.
///
/// On success returns the HTTP response status code from the server; on failure returns the underlying `reqwest::Error`.
///
/// # Examples
///
/// ```no_run
/// use api::Client;
///
/// let client = Client::new("http://127.0.0.1".into(), None);
/// let status = tokio::runtime::Runtime::new()
/// .unwrap()
/// .block_on(client.clear_done())
/// .unwrap();
/// assert!(status.is_success());
/// ```
pub async fn clear_done(&self) -> Result<StatusCode, Error> {
let result = self.client
.delete(format!("{}:{}/cleardone", self.hostname, self.port).as_str())
.send().await;
match result {
Ok(result) => Ok(result.status()),
Err(err) => {Err(err)}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn get() {
let client = Client::new("http://127.0.0.1".to_string(), None);
let result = client.get().await;
println!("{:?}", result);
assert!(result.is_ok() && result.unwrap().0 == StatusCode::OK);
}
#[tokio::test]
async fn add_get_index_done_undone_remove() {
let client = Client::new("http://127.0.0.1".to_string(), None);
// add
let result = client.add(&"test".to_string()).await;
println!("{:?}", result);
assert!(result.is_ok() && result.unwrap().0 == StatusCode::OK);
// get_index
let result = client.get_index(&"test".to_string()).await;
println!("{:?}", result);
assert!(result.is_ok() && result.unwrap().0 == StatusCode::OK);
// done
let result = client.done(&"test".to_string()).await;
println!("{:?}", result);
assert!(result.is_ok() && result.unwrap().0 == StatusCode::OK);
// undone
let result = client.undone(&"test".to_string()).await;
println!("{:?}", result);
assert!(result.is_ok() && result.unwrap().0 == StatusCode::OK);
// remove
let result = client.remove(&"test".to_string()).await;
println!("{:?}", result);
assert!(result.is_ok() && result.unwrap() == StatusCode::OK);
}
#[tokio::test]
async fn clear() {
let client = Client::new("http://127.0.0.1".to_string(), None);
let _ = client.add(&"test".to_string()).await;
let _ = client.add(&"test".to_string()).await;
let _ = client.add(&"test".to_string()).await;
let result = client.clear().await;
println!("{:?}", result);
assert!(result.is_ok());
let result = client.get().await;
println!("{:?}", result);
assert!(result.is_ok());
let unwrapped = result.unwrap();
assert!(unwrapped.0 == StatusCode::OK && unwrapped.1.len() == 0);
}
#[tokio::test]
async fn clear_done() {
let client = Client::new("http://127.0.0.1".to_string(), None);
let _ = client.add(&"test1".to_string()).await;
let _ = client.add(&"test2".to_string()).await;
let _ = client.add(&"test3".to_string()).await;
let _ = client.done(&"test1".to_string()).await;
let _ = client.done(&"test3".to_string()).await;
let result = client.clear_done().await;
println!("{:?}", result);
assert!(result.is_ok());
let result = client.get().await;
println!("{:?}", result);
assert!(result.is_ok());
let unwrapped = result.unwrap();
assert!(unwrapped.0 == StatusCode::OK
&& unwrapped.1.len() == 1
&& unwrapped.1[0].name == "test2");
}
}