use reqwest::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>;
}
#[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 },
}
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: &str, body: I) -> anyhow::Result<O>
where
I: Serialize,
O: DeserializeOwned,
{
let response = self
.client
.post(self.base.join(endpoint)?)
.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("login", request).await
}
}