trakt_core/request.rs
1use bytes::BufMut;
2use http::Method;
3
4use crate::{error::IntoHttpError, response::Response};
5
6/// Trait for requests.
7///
8/// All requests in the API should implement this trait.
9/// It provides a method to convert the request into an HTTP request.
10///
11/// The implementing type can perform any necessary validation on the request before converting it
12/// into an HTTP request.
13///
14/// The [`Self::Response`] associated type is the type that should be used to represent the response
15/// returned by the server.
16pub trait Request: Sized + Clone {
17 type Response: Response;
18
19 /// The metadata for the request.
20 const METADATA: Metadata;
21
22 /// Tries to convert the request into an HTTP request.
23 ///
24 /// On endpoints requiring authentication, the `token` field in `ctx` should be provided.
25 /// If not, the request will fail to convert.
26 ///
27 /// # Arguments
28 ///
29 /// * `ctx`: The context for the request.
30 ///
31 /// # Errors
32 /// This function will return an error if the request cannot be converted into an HTTP request.
33 fn try_into_http_request<T: Default + BufMut>(
34 self,
35 ctx: Context,
36 ) -> Result<http::Request<T>, IntoHttpError>;
37}
38
39/// Represents metadata for an API endpoint.
40///
41/// This struct holds information about the endpoint, such as the URL endpoint, HTTP method, and
42/// authorization requirement.
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct Metadata {
45 /// The URL endpoint for the request.
46 pub endpoint: &'static str,
47 /// The HTTP method for the request.
48 pub method: Method,
49 /// Authorization requirement for the request.
50 pub auth: AuthRequirement,
51}
52
53/// Authorization requirement for an API request.
54#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
55pub enum AuthRequirement {
56 /// No authorization required.
57 #[default]
58 None,
59 /// Authorization is optional. Request may behave differently based on the presence of a token.
60 Optional,
61 /// Authorization is required. Request will fail if no token is provided.
62 Required,
63}
64
65/// Represents the universal context for an API request.
66///
67/// This struct contains the information needed to make an API request, such as the base URL,
68/// client ID, and OAuth token if available.
69#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
70pub struct Context<'a> {
71 /// The base URL for the API.
72 pub base_url: &'a str,
73 /// The client ID for the API.
74 pub client_id: &'a str,
75 /// The OAuth token for the API, if requesting an authenticated endpoint.
76 pub oauth_token: Option<&'a str>,
77}