Add RequestParts::extract (#897)

This commit is contained in:
Jonas Platte 2022-04-01 09:25:15 +02:00 committed by GitHub
parent 956c9f1d88
commit 1191b58083
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 2 deletions

View file

@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased
- None.
- **added:** Add `RequestParts::extract` which allows applying an extractor as a method call
# 0.2.0 (31. March, 2022)

View file

@ -113,6 +113,38 @@ impl<B> RequestParts<B> {
}
}
/// Apply an extractor to this `RequestParts`.
///
/// `req.extract::<Extractor>()` is equivalent to `Extractor::from_request(req)`.
/// This function simply exists as a convenience.
///
/// # Example
///
/// ```
/// # struct MyExtractor {}
///
/// use std::convert::Infallible;
///
/// use async_trait::async_trait;
/// use axum::extract::{FromRequest, RequestParts};
/// use http::{Method, Uri};
///
/// #[async_trait]
/// impl<B: Send> FromRequest<B> for MyExtractor {
/// type Rejection = Infallible;
///
/// async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Infallible> {
/// let method = req.extract::<Method>().await?;
/// let path = req.extract::<Uri>().await?.path().to_owned();
///
/// todo!()
/// }
/// }
/// ```
pub async fn extract<E: FromRequest<B>>(&mut self) -> Result<E, E::Rejection> {
E::from_request(self).await
}
/// Convert this `RequestParts` back into a [`Request`].
///
/// Fails if The request body has been extracted, that is [`take_body`] has

View file

@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased
- None.
- **added:** Add `RequestParts::extract` which allows applying an extractor as a method call
# 0.5.0 (31. March, 2022)