use anyhow::bail;
use anyhow::Result;
use libtaskrs::task::{TaskId, TaskRequest, TaskResponse};
use log::debug;
use reqwest::Response;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
pub struct TaskClient {
client: Client,
base_url: String,
task_url: String,
}
impl TaskClient {
pub fn new(base_url: &str, app_name: &str, app_version: &str) -> Result<Self> {
let user_agent = format!("{}/{}", app_name, app_version);
let client = ClientBuilder::new().user_agent(user_agent).build().unwrap();
let mut base_url = base_url.to_string();
base_url.push_str("/api/v1");
let mut task_url = base_url.clone();
task_url.push_str("/tasks");
Ok(Self {
client,
base_url,
task_url,
})
}
async fn get(&self, url: &str) -> Result<Response> {
let response = self
.client
.get(url)
.send()
.await
.expect("Unable to contact server");
debug!("Status code: {}", response.status());
if let Err(e) = response.error_for_status_ref() {
bail!("Server returned error: {}", e);
}
Ok(response)
}
pub async fn get_all_tasks(&self) -> Result<Vec<TaskResponse>> {
let r = self.get(&self.task_url).await?;
let tasks = r.json::<Vec<TaskResponse>>().await.unwrap();
Ok(tasks)
}
pub async fn get_task(&self, id: TaskId) -> Result<TaskResponse> {
let url = format!("{}/{}", self.task_url, id);
let r = self.get(&url).await?;
let task = r.json::<TaskResponse>().await.unwrap();
Ok(task)
}
pub async fn add_task(&self, task: TaskRequest) -> Result<TaskId> {
let r = self
.client
.post(&self.task_url)
.json(&task)
.send()
.await
.unwrap();
if let Err(e) = r.error_for_status_ref() {
bail!("Server returned error: {}", e);
}
let id = r.json::<TaskId>().await.unwrap();
Ok(id)
}
pub async fn update_task(&self, id: TaskId, updated_task: TaskRequest) -> Result<()> {
let url = format!("{}/{}", self.task_url, id);
let r = self
.client
.post(&url)
.json(&updated_task)
.send()
.await
.unwrap();
if let Err(e) = r.error_for_status_ref() {
bail!("Server returned error: {}", e);
}
Ok(())
}
pub async fn delete_task(&self, id: TaskId) -> Result<()> {
let url = format!("{}/{}", self.task_url, id);
let r = self.client.delete(&url).send().await.unwrap();
if let Err(e) = r.error_for_status_ref() {
bail!("Server returned error: {}", e);
}
Ok(())
}
}