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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use std::collections::HashMap;
use std::time::Duration;

use crate::{
    from_json, get_driver, FetchMethod, JsJson, JsJsonDeserialize, JsJsonSerialize, LazyCache,
};

#[derive(Debug, Clone)]
pub enum RequestBody {
    Text(String),
    Json(JsJson),
    Binary(Vec<u8>),
}

impl RequestBody {
    pub fn into<T: JsJsonDeserialize>(self) -> Result<T, String> {
        match self {
            RequestBody::Json(json) => match from_json::<T>(json) {
                Ok(data) => Ok(data),
                Err(err) => Err(err),
            },
            RequestBody::Text(_) => {
                Err("FetchBody.into() - expected json, received text".to_string())
            }
            RequestBody::Binary(_) => {
                Err("FetchBody.into() - expected json, received binary".to_string())
            }
        }
    }
}

/// Builder for typed requests.
#[derive(Clone)]
pub struct RequestBuilder {
    method: FetchMethod,
    url: String,
    headers: HashMap<String, String>,
    body: Option<RequestBody>,
    ttl: Option<Duration>,
}

impl RequestBuilder {
    pub fn new(method: FetchMethod, url: impl Into<String>) -> Self {
        Self {
            method,
            url: url.into(),
            headers: HashMap::new(),
            body: None,
            ttl: None,
        }
    }

    #[must_use]
    pub fn get(url: impl Into<String>) -> Self {
        Self::new(FetchMethod::GET, url)
    }

    #[must_use]
    pub fn post(url: impl Into<String>) -> Self {
        Self::new(FetchMethod::POST, url)
    }

    #[must_use]
    pub fn body(mut self, body: RequestBody) -> Self {
        self.body = Some(body);
        self
    }

    #[must_use]
    pub fn bearer_auth(self, token: impl Into<String>) -> Self {
        let token: String = token.into();
        self.set_header("Authorization", format!("Bearer {token}"))
    }

    #[must_use]
    pub fn set_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        let name: String = name.into();
        let value: String = value.into();
        self.headers.insert(name, value);
        self
    }

    #[must_use]
    pub fn body_json(self, body: impl JsJsonSerialize) -> Self {
        let body = body.to_json();
        self.body(RequestBody::Json(body))
    }

    #[must_use]
    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
        self.headers = headers;
        self
    }

    #[must_use]
    pub fn ttl_seconds(mut self, seconds: u64) -> Self {
        self.ttl = Some(Duration::from_secs(seconds));
        self
    }

    #[must_use]
    pub fn ttl_minutes(mut self, minutes: u64) -> Self {
        self.ttl = Some(Duration::from_secs(minutes * 60));
        self
    }

    #[must_use]
    pub fn ttl_hours(mut self, hours: u64) -> Self {
        self.ttl = Some(Duration::from_secs(hours * 60 * 60));
        self
    }

    #[must_use]
    pub fn ttl_days(mut self, days: u64) -> Self {
        self.ttl = Some(Duration::from_secs(days * 24 * 60 * 60));
        self
    }

    #[must_use]
    pub fn get_ttl(&self) -> Option<Duration> {
        self.ttl
    }

    pub async fn call(&self) -> RequestResponse {
        let Self {
            method,
            url,
            headers,
            body,
            ttl: _,
        } = self;

        let result = get_driver()
            .inner
            .api
            .fetch(*method, url.clone(), Some(headers.clone()), body.clone())
            .await;

        RequestResponse::new(*method, url.clone(), result)
    }

    #[must_use]
    pub fn lazy_cache<T>(
        self,
        map_response: impl Fn(u32, RequestBody) -> Option<Result<T, String>> + 'static,
    ) -> LazyCache<T> {
        LazyCache::new(self, map_response)
    }
}

/// Result from request made using [RequestBuilder].
#[derive(Debug)]
pub struct RequestResponse {
    method: FetchMethod,
    url: String,
    data: Result<(u32, RequestBody), String>,
}

impl RequestResponse {
    fn new(
        method: FetchMethod,
        url: String,
        data: Result<(u32, RequestBody), String>,
    ) -> RequestResponse {
        RequestResponse { method, url, data }
    }

    pub fn status(&self) -> Option<u32> {
        if let Ok((status, _)) = self.data {
            return Some(status);
        }

        None
    }

    pub fn into<T>(
        self,
        convert: impl Fn(u32, RequestBody) -> Option<Result<T, String>>,
    ) -> Result<T, String> {
        let result = match self.data {
            Ok((status, body)) => match convert(status, body) {
                Some(result) => result,
                None => Err(format!("Unhandled response code {status}")),
            },
            Err(err) => Err(err),
        };

        if let Err(err) = &result {
            log::error!(
                "Error fetching {} {}: {}",
                self.method.to_str(),
                self.url,
                err
            );
        }

        result
    }

    pub fn into_data<T: JsJsonDeserialize>(self) -> Result<T, String> {
        self.into(|_, response_body| Some(response_body.into::<T>()))
    }

    pub fn into_error_message<T>(self) -> Result<T, String> {
        let body = match self.data {
            Ok((code, body)) => format!("API error {code}: {body:#?}"),
            Err(body) => format!("Network error: {body}"),
        };

        Err(body)
    }
}