use reqwest::{header, Client};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use url::Url;
#[async_trait::async_trait]
pub trait Api {
async fn login(&self, request: LoginRequest) -> anyhow::Result<LoginResponse>;
async fn create_project(
&self,
request: CreateProjectRequest,
token: String,
) -> anyhow::Result<CreateProjectResponse>;
async fn register_task_version(
&self,
request: CreateTaskVersionRequest,
token: String,
) -> anyhow::Result<CreateTaskVersionResponse>;
}
#[derive(Serialize, Deserialize)]
pub struct Error {
pub message: String,
pub chain: Vec<String>,
}
impl<'a> From<&'a anyhow::Error> for Error {
fn from(err: &'a anyhow::Error) -> Self {
Error {
message: err.to_string(),
chain: err.chain().map(|e| e.to_string()).collect::<Vec<_>>(),
}
}
}
impl From<Error> for anyhow::Error {
fn from(value: Error) -> Self {
match value.chain.as_slice() {
[] => anyhow::Error::msg(value.message),
[head @ .., last] => head
.into_iter()
.rev()
.fold(anyhow::Error::msg(last.to_string()), |e, m| {
e.context(m.to_string())
}),
}
}
}
#[derive(Serialize, Deserialize)]
pub struct LoginRequest {
pub email: String,
pub password: String,
}
#[derive(Serialize, Deserialize)]
pub enum LoginResponse {
CreatedAccount { email: String, token: String },
LoggedIn { email: String, token: String },
}
#[derive(Serialize, Deserialize)]
pub struct CreateProjectRequest {
pub nickname: Option<String>,
}
#[derive(Serialize, Deserialize)]
pub struct CreateProjectResponse {
pub id: String,
pub nickname: Option<String>,
}
#[derive(Serialize, Deserialize)]
pub struct CreateTaskVersionRequest {
pub project_id: String,
pub task_id: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CreateTaskVersionResponse {
pub project_id: String,
pub task_id: String,
pub hash: String,
pub created_at: chrono::NaiveDateTime,
}
#[derive(Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Method {
Login,
CreateProject,
RegisterTaskVersion,
}
pub struct HttpApi {
client: Client,
base: Url,
}
impl HttpApi {
pub fn new(base: &Url) -> anyhow::Result<Self> {
anyhow::ensure!(base.as_str().ends_with("/"), "API url must end with a /");
Ok(Self {
client: Client::new(),
base: base.clone(),
})
}
async fn call_endpoint<I, O>(
&self,
endpoint: Method,
body: I,
token: impl Into<Option<String>>,
) -> anyhow::Result<O>
where
I: Serialize,
O: DeserializeOwned,
{
let url = self.base.join(&serde_json::to_string(&endpoint)?)?;
let request = self.client.post(url);
let request = if let Some(token) = token.into() {
request.header(header::AUTHORIZATION, format!("Bearer {token}"))
} else {
request
};
let response = request.json(&body).send().await?;
let status = response.status();
if status.is_success() {
Ok(response.json().await?)
} else if status.is_client_error() || status.is_server_error() {
Err(response.json::<Error>().await?.into())
} else {
anyhow::bail!("Unhandled error code {}", status);
}
}
}
#[async_trait::async_trait]
impl Api for HttpApi {
async fn login(&self, request: LoginRequest) -> anyhow::Result<LoginResponse> {
self.call_endpoint(Method::Login, request, None).await
}
async fn create_project(
&self,
request: CreateProjectRequest,
token: String,
) -> anyhow::Result<CreateProjectResponse> {
self.call_endpoint(Method::CreateProject, request, token)
.await
}
async fn register_task_version(
&self,
request: CreateTaskVersionRequest,
token: String,
) -> anyhow::Result<CreateTaskVersionResponse> {
self.call_endpoint(Method::RegisterTaskVersion, request, token)
.await
}
}