better-fetch 0.3.0

Typed HTTP client layer on top of reqwest — inspired by @better-fetch/fetch
Documentation
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Typed API routes via the [`Endpoint`] trait.
//!
//! Define routes as types, then use [`Client::call`](crate::Client::call) for a typed
//! [`EndpointRequestBuilder`]. Path and query use [`.params()`](EndpointRequestBuilder::params)
//! and [`.query()`](EndpointRequestBuilder::query) with structs — not string keys.
//!
//! For ad-hoc string paths, use [`Client::get`](crate::Client::get) instead (see [`RequestBuilder`](crate::RequestBuilder)).
//!
//! Helpers: [`endpoint!`], [`define_params!`], and (feature `macros`) `EndpointParamsDerive` /
//! `EndpointQueryDerive`.

use std::marker::PhantomData;

use http::Method;
use indexmap::IndexMap;

use crate::request::RequestBuilder;
use crate::url_build::QueryValue;

#[cfg(feature = "json")]
use serde::de::DeserializeOwned;

/// Type-state: path parameters still required before send.
#[derive(Debug, Clone, Copy, Default)]
pub struct NeedsParams;

/// Type-state: ready to configure query/headers and send.
#[derive(Debug, Clone, Copy, Default)]
pub struct Ready;

/// Describes a typed API route.
///
/// Implement this trait (or use [`endpoint!`]) and call [`Client::call`](crate::Client::call).
/// Path and query parameters are typed via [`EndpointParams`] and [`EndpointQuery`] structs;
/// use [`.params()`](EndpointRequestBuilder::params) and [`.query()`](EndpointRequestBuilder::query).
///
/// # Examples
///
/// ```no_run
/// # use better_fetch::{Client, Endpoint, EndpointParams, Result, define_params};
/// # use http::Method;
/// # use serde::Deserialize;
/// define_params!(GetTodoParams for "/todos/:id" { id: u64 });
///
/// struct GetTodo;
///
/// impl Endpoint for GetTodo {
///     const METHOD: Method = Method::GET;
///     const PATH: &'static str = "/todos/:id";
///     type Response = Todo;
///     type Params = GetTodoParams;
///     type Query = ();
/// }
///
/// #[derive(Deserialize)]
/// struct Todo { id: u64, title: String }
///
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let client = Client::new("https://jsonplaceholder.typicode.com")?;
/// let todo: Todo = client
///     .call::<GetTodo>()
///     .params(GetTodoParams { id: 1 })
///     .send_json()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub trait Endpoint {
    /// HTTP method for this route.
    const METHOD: Method;
    /// Path template (may include `:param` segments).
    const PATH: &'static str;

    #[cfg(feature = "json")]
    /// JSON response type for [`EndpointRequestBuilder::send_json`].
    type Response: DeserializeOwned;

    #[cfg(not(feature = "json"))]
    /// Response type when the `json` feature is disabled.
    type Response;

    /// Path parameters applied via [`EndpointRequestBuilder::params`].
    type Params: EndpointParams + Default;
    /// Query parameters applied via [`EndpointRequestBuilder::query`].
    type Query: EndpointQuery + Default;
}

/// Initial builder state for an endpoint's path parameters.
pub type ParamsBuilderState<P> = <P as EndpointParams>::BuilderState;

/// Creates the initial [`EndpointRequestBuilder`] for `client.call::<E>()`.
pub trait EndpointParamsInitial<E: Endpoint>: EndpointParams {
    fn initial(client: &crate::Client) -> EndpointRequestBuilder<'_, E, Self::BuilderState>;
}

impl<E: Endpoint> EndpointParamsInitial<E> for () {
    fn initial(client: &crate::Client) -> EndpointRequestBuilder<'_, E, Ready> {
        EndpointRequestBuilder::new_ready(client.request(E::METHOD, E::PATH))
    }
}

impl<E: Endpoint, P: EndpointParams<BuilderState = NeedsParams>> EndpointParamsInitial<E> for P {
    fn initial(client: &crate::Client) -> EndpointRequestBuilder<'_, E, NeedsParams> {
        EndpointRequestBuilder::new_needs_params(client.request(E::METHOD, E::PATH))
    }
}

/// Applies path parameters to a [`RequestBuilder`].
pub trait EndpointParams: Default + Sized {
    /// When [`NeedsParams`], [`.params()`](EndpointRequestBuilder::params) is required before send.
    type BuilderState;
    /// Applies this type's parameters to `builder`.
    fn apply_params(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_>;
}

impl EndpointParams for () {
    type BuilderState = Ready;

    fn apply_params(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_> {
        builder
    }
}

impl EndpointParams for std::collections::HashMap<String, String> {
    type BuilderState = NeedsParams;

    fn apply_params(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_> {
        builder.params(self)
    }
}

impl EndpointParams for Vec<(String, String)> {
    type BuilderState = NeedsParams;

    fn apply_params(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_> {
        builder.params_iter(self)
    }
}

/// Applies query parameters to a [`RequestBuilder`].
pub trait EndpointQuery {
    /// Applies this type's query map to `builder`.
    fn apply_query(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_>;
}

impl EndpointQuery for () {
    fn apply_query(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_> {
        builder
    }
}

impl EndpointQuery for IndexMap<String, QueryValue> {
    fn apply_query(self, builder: RequestBuilder<'_>) -> RequestBuilder<'_> {
        builder.queries(self)
    }
}

/// Applies a serde-serializable query struct to a request builder (feature `json`).
#[cfg(feature = "json")]
pub fn apply_serialized_query<T: serde::Serialize>(
    query: T,
    builder: RequestBuilder<'_>,
) -> RequestBuilder<'_> {
    match crate::url_build::serialize_to_query_map(&query) {
        Ok(map) => builder.queries(map),
        Err(_) => builder,
    }
}

/// Fluent builder for a typed [`Endpoint`].
///
/// When `E::Params` is not [`()`], the builder starts in [`NeedsParams`] and requires
/// [`.params()`](Self::params) before [`.send_json()`](Self::send_json).
pub struct EndpointRequestBuilder<'a, E: Endpoint, S> {
    pub(crate) inner: RequestBuilder<'a>,
    _marker: PhantomData<(E, S)>,
}

impl<'a, E: Endpoint> EndpointRequestBuilder<'a, E, NeedsParams> {
    pub(crate) fn new_needs_params(inner: RequestBuilder<'a>) -> Self {
        Self {
            inner,
            _marker: PhantomData,
        }
    }

    /// Applies typed path parameters for `E::Params` and transitions to [`Ready`].
    pub fn params(self, params: E::Params) -> EndpointRequestBuilder<'a, E, Ready> {
        EndpointRequestBuilder {
            inner: params.apply_params(self.inner),
            _marker: PhantomData,
        }
    }
}

impl<'a, E: Endpoint> EndpointRequestBuilder<'a, E, Ready> {
    pub(crate) fn new_ready(inner: RequestBuilder<'a>) -> Self {
        Self {
            inner,
            _marker: PhantomData,
        }
    }

    /// Applies typed query parameters for `E::Query`.
    pub fn query(self, query: E::Query) -> Self {
        Self {
            inner: query.apply_query(self.inner),
            _marker: PhantomData,
        }
    }

    /// Adds a request header.
    pub fn header(self, key: impl AsRef<str>, value: impl AsRef<str>) -> crate::Result<Self> {
        Ok(Self {
            inner: self.inner.header(key, value)?,
            _marker: PhantomData,
        })
    }

    /// Sets bearer authentication.
    pub fn bearer_token(self, token: impl Into<String>) -> Self {
        Self {
            inner: self.inner.bearer_token(token),
            _marker: PhantomData,
        }
    }

    /// Attaches a cancellation token.
    pub fn cancellation_token(self, token: crate::CancellationToken) -> Self {
        Self {
            inner: self.inner.cancellation_token(token),
            _marker: PhantomData,
        }
    }

    /// When `true`, [`send`](Self::send) returns `Err` on non-2xx.
    pub fn throw_on_error(self, throw: bool) -> Self {
        Self {
            inner: self.inner.throw_on_error(throw),
            _marker: PhantomData,
        }
    }

    /// Executes the request and returns [`Response`](crate::Response).
    pub async fn send(self) -> crate::Result<crate::Response> {
        self.inner.send().await
    }

    /// Executes and deserializes `E::Response` (feature `json`).
    #[cfg(feature = "json")]
    pub async fn send_json(self) -> crate::Result<E::Response> {
        self.inner.send().await?.json::<E::Response>().await
    }

    /// Returns the underlying [`RequestBuilder`] for advanced options.
    pub fn into_inner(self) -> RequestBuilder<'a> {
        self.inner
    }
}

/// Defines path parameters for a route and implements [`EndpointParams`].
///
/// Each struct field maps to a `:field` segment in `path` (by field name).
/// For compile-time path validation, use `#[derive(EndpointParamsDerive)]` (feature `macros`).
///
/// # Examples
///
/// ```
/// use better_fetch::{define_params, EndpointParams, NeedsParams};
///
/// define_params!(GetTodoParams for "/todos/:id" { id: u64 });
///
/// fn assert_needs_params<T: EndpointParams<BuilderState = NeedsParams>>() {}
/// assert_needs_params::<GetTodoParams>();
/// ```
#[macro_export]
macro_rules! define_params {
    (
        $name:ident for $path:literal {
            $( $field:ident : $ty:ty ),* $(,)?
        }
    ) => {
        #[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
        pub struct $name {
            $( pub $field: $ty, )*
        }

        impl $crate::EndpointParams for $name {
            type BuilderState = $crate::NeedsParams;

            fn apply_params(self, builder: $crate::RequestBuilder<'_>) -> $crate::RequestBuilder<'_> {
                let builder = builder;
                $(
                    let builder = builder.param(stringify!($field), self.$field);
                )*
                builder
            }
        }
    };
}

/// Implements [`EndpointQuery`] for a serde-serializable query struct (feature `json`).
#[cfg(feature = "json")]
#[macro_export]
macro_rules! impl_serde_endpoint_query {
    ($ty:ty) => {
        impl $crate::EndpointQuery for $ty {
            fn apply_query(
                self,
                builder: $crate::RequestBuilder<'_>,
            ) -> $crate::RequestBuilder<'_> {
                $crate::endpoint::apply_serialized_query(self, builder)
            }
        }
    };
}

/// Defines a simple [`Endpoint`] with optional typed params and query.
///
/// # Examples
///
/// ```
/// use better_fetch::{endpoint, define_params};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// pub struct Health {
///     ok: bool,
/// }
///
/// endpoint!(HealthCheck, GET, "/health", Response = Health);
///
/// define_params!(GetTodoParams for "/todos/:id" { id: u64 });
/// endpoint!(GetTodo, GET, "/todos/:id", Response = Health, Params = GetTodoParams);
/// ```
#[macro_export]
macro_rules! endpoint {
    (
        $name:ident,
        $method:ident,
        $path:literal,
        Response = $response:ty
    ) => {
        $crate::endpoint!(
            $name,
            $method,
            $path,
            Response = $response,
            Params = (),
            Query = ()
        );
    };
    (
        $name:ident,
        $method:ident,
        $path:literal,
        Response = $response:ty,
        Params = $params:ty
    ) => {
        $crate::endpoint!(
            $name,
            $method,
            $path,
            Response = $response,
            Params = $params,
            Query = ()
        );
    };
    (
        $name:ident,
        $method:ident,
        $path:literal,
        Response = $response:ty,
        Query = $query:ty
    ) => {
        $crate::endpoint!(
            $name,
            $method,
            $path,
            Response = $response,
            Params = (),
            Query = $query
        );
    };
    (
        $name:ident,
        $method:ident,
        $path:literal,
        Response = $response:ty,
        Params = $params:ty,
        Query = $query:ty
    ) => {
        pub struct $name;
        impl $crate::Endpoint for $name {
            const METHOD: http::Method = http::Method::$method;
            const PATH: &'static str = $path;
            type Response = $response;
            type Params = $params;
            type Query = $query;
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    define_params!(TestParams for "/items/:id" { id: u64 });

    #[test]
    fn params_builder_state_is_needs_params() {
        fn assert_needs<T: EndpointParams<BuilderState = NeedsParams>>() {}
        assert_needs::<TestParams>();
    }

    #[test]
    fn unit_params_builder_state_is_ready() {
        fn assert_ready<T: EndpointParams<BuilderState = Ready>>() {}
        assert_ready::<()>();
    }
}