axum_core/extract/
option.rs

1use std::future::Future;
2
3use http::request::Parts;
4
5use crate::response::IntoResponse;
6
7use super::{private, FromRequest, FromRequestParts, Request};
8
9/// Customize the behavior of `Option<Self>` as a [`FromRequestParts`]
10/// extractor.
11pub trait OptionalFromRequestParts<S>: Sized {
12    /// If the extractor fails, it will use this "rejection" type.
13    ///
14    /// A rejection is a kind of error that can be converted into a response.
15    type Rejection: IntoResponse;
16
17    /// Perform the extraction.
18    fn from_request_parts(
19        parts: &mut Parts,
20        state: &S,
21    ) -> impl Future<Output = Result<Option<Self>, Self::Rejection>> + Send;
22}
23
24/// Customize the behavior of `Option<Self>` as a [`FromRequest`] extractor.
25pub trait OptionalFromRequest<S, M = private::ViaRequest>: Sized {
26    /// If the extractor fails, it will use this "rejection" type.
27    ///
28    /// A rejection is a kind of error that can be converted into a response.
29    type Rejection: IntoResponse;
30
31    /// Perform the extraction.
32    fn from_request(
33        req: Request,
34        state: &S,
35    ) -> impl Future<Output = Result<Option<Self>, Self::Rejection>> + Send;
36}
37
38// Compiler hint just says that there is an impl for Option<T>, not mentioning
39// the bounds, which is not very helpful.
40#[diagnostic::do_not_recommend]
41impl<S, T> FromRequestParts<S> for Option<T>
42where
43    T: OptionalFromRequestParts<S>,
44    S: Send + Sync,
45{
46    type Rejection = T::Rejection;
47
48    #[allow(clippy::use_self)]
49    fn from_request_parts(
50        parts: &mut Parts,
51        state: &S,
52    ) -> impl Future<Output = Result<Option<T>, Self::Rejection>> {
53        T::from_request_parts(parts, state)
54    }
55}
56
57#[diagnostic::do_not_recommend]
58impl<S, T> FromRequest<S> for Option<T>
59where
60    T: OptionalFromRequest<S>,
61    S: Send + Sync,
62{
63    type Rejection = T::Rejection;
64
65    #[allow(clippy::use_self)]
66    async fn from_request(req: Request, state: &S) -> Result<Option<T>, Self::Rejection> {
67        T::from_request(req, state).await
68    }
69}