This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, RescheduleTask, Routine, Task};
|
||||
|
||||
pub struct ApiClient {
|
||||
base_url: String,
|
||||
token: Option<String>,
|
||||
}
|
||||
|
||||
impl ApiClient {
|
||||
pub fn new(base_url: String, token: Option<String>) -> Self {
|
||||
Self {
|
||||
base_url: base_url.trim_end_matches('/').to_owned(),
|
||||
token,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_tasks(&self, date: &str) -> Result<Vec<Task>, String> {
|
||||
self.get(&format!("/v1/tasks?date={date}"))
|
||||
}
|
||||
|
||||
pub fn list_routines(&self) -> Result<Vec<Routine>, String> {
|
||||
self.get("/v1/routines")
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: &CreateTask) -> Result<(), String> {
|
||||
self.send_json("/v1/tasks", task)
|
||||
}
|
||||
|
||||
pub fn create_routine(&self, routine: &CreateRoutine) -> Result<(), String> {
|
||||
self.send_json("/v1/routines", routine)
|
||||
}
|
||||
|
||||
pub fn complete_task(&self, id: i64) -> Result<(), String> {
|
||||
self.send_empty("POST", &format!("/v1/tasks/{id}/complete"))
|
||||
}
|
||||
|
||||
pub fn delete_task(&self, id: i64) -> Result<(), String> {
|
||||
self.send_empty("DELETE", &format!("/v1/tasks/{id}"))
|
||||
}
|
||||
|
||||
pub fn reschedule_task(&self, id: i64, date: &str) -> Result<(), String> {
|
||||
self.send_json(
|
||||
&format!("/v1/tasks/{id}/reschedule"),
|
||||
&RescheduleTask {
|
||||
scheduled_date: date.to_owned(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, String> {
|
||||
let response = self
|
||||
.authorize(minreq::get(self.url(path)))
|
||||
.send()
|
||||
.map_err(transport_error)?;
|
||||
let body = response.as_str().map_err(|error| error.to_string())?;
|
||||
if !(200..300).contains(&response.status_code) {
|
||||
return Err(api_error(response.status_code, body));
|
||||
}
|
||||
serde_json::from_str(body).map_err(|error| format!("invalid server response: {error}"))
|
||||
}
|
||||
|
||||
fn send_json<T: Serialize>(&self, path: &str, value: &T) -> Result<(), String> {
|
||||
let body = serde_json::to_string(value).map_err(|error| error.to_string())?;
|
||||
let response = self
|
||||
.authorize(minreq::post(self.url(path)))
|
||||
.with_header("Content-Type", "application/json")
|
||||
.with_body(body)
|
||||
.send()
|
||||
.map_err(transport_error)?;
|
||||
check_status(response)
|
||||
}
|
||||
|
||||
fn send_empty(&self, method: &str, path: &str) -> Result<(), String> {
|
||||
let request = match method {
|
||||
"POST" => minreq::post(self.url(path)),
|
||||
"DELETE" => minreq::delete(self.url(path)),
|
||||
_ => return Err(format!("unsupported HTTP method: {method}")),
|
||||
};
|
||||
let response = self.authorize(request).send().map_err(transport_error)?;
|
||||
check_status(response)
|
||||
}
|
||||
|
||||
fn authorize(&self, request: minreq::Request) -> minreq::Request {
|
||||
match &self.token {
|
||||
Some(token) => request.with_header("Authorization", format!("Bearer {token}")),
|
||||
None => request,
|
||||
}
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}{path}", self.base_url)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_status(response: minreq::Response) -> Result<(), String> {
|
||||
if (200..300).contains(&response.status_code) {
|
||||
return Ok(());
|
||||
}
|
||||
let body = response.as_str().unwrap_or("");
|
||||
Err(api_error(response.status_code, body))
|
||||
}
|
||||
|
||||
fn api_error(status: i32, body: &str) -> String {
|
||||
serde_json::from_str::<serde_json::Value>(body)
|
||||
.ok()
|
||||
.and_then(|value| value["error"].as_str().map(str::to_owned))
|
||||
.unwrap_or_else(|| format!("server returned HTTP {status}"))
|
||||
}
|
||||
|
||||
fn transport_error(error: minreq::Error) -> String {
|
||||
format!("cannot reach routine-server: {error}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn joins_base_url_and_path_once() {
|
||||
let client = ApiClient::new("http://localhost:8090/".to_owned(), None);
|
||||
assert_eq!(client.url("/health"), "http://localhost:8090/health");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_json_error_message() {
|
||||
assert_eq!(api_error(400, r#"{"error":"bad date"}"#), "bad date");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user