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
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
    }
}