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
38impl<S, T> FromRequestParts<S> for Option<T>
39where
40    T: OptionalFromRequestParts<S>,
41    S: Send + Sync,
42{
43    type Rejection = T::Rejection;
44
45    fn from_request_parts(
46        parts: &mut Parts,
47        state: &S,
48    ) -> impl Future<Output = Result<Option<T>, Self::Rejection>> {
49        T::from_request_parts(parts, state)
50    }
51}
52
53impl<S, T> FromRequest<S> for Option<T>
54where
55    T: OptionalFromRequest<S>,
56    S: Send + Sync,
57{
58    type Rejection = T::Rejection;
59
60    async fn from_request(req: Request, state: &S) -> Result<Option<T>, Self::Rejection> {
61        T::from_request(req, state).await
62    }
63}