Skip to main content

better_fetch/
endpoint.rs

1use http::Method;
2
3use crate::client::Client;
4use crate::request::RequestBuilder;
5
6#[cfg(feature = "json")]
7use serde::de::DeserializeOwned;
8
9/// Describes a typed API route.
10pub trait Endpoint {
11    const METHOD: Method;
12    const PATH: &'static str;
13
14    #[cfg(feature = "json")]
15    type Response: DeserializeOwned;
16
17    #[cfg(not(feature = "json"))]
18    type Response;
19
20    type Params: Default;
21    type Query: Default;
22}
23
24impl Client {
25    /// Start a request for a typed [`Endpoint`].
26    pub fn call<E: Endpoint>(&self) -> RequestBuilder<'_> {
27        self.request(E::METHOD, E::PATH)
28    }
29}
30
31/// Helper macro for simple endpoint definitions.
32#[macro_export]
33macro_rules! endpoint {
34    (
35        $name:ident,
36        $method:ident,
37        $path:literal,
38        Response = $response:ty
39    ) => {
40        pub struct $name;
41        impl $crate::Endpoint for $name {
42            const METHOD: http::Method = http::Method::$method;
43            const PATH: &'static str = $path;
44            type Response = $response;
45            type Params = ();
46            type Query = ();
47        }
48    };
49}