From 1191b58083b1a4684ed5367ca427292de5e102f6 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Fri, 1 Apr 2022 09:25:15 +0200 Subject: [PATCH] Add `RequestParts::extract` (#897) --- axum-core/CHANGELOG.md | 2 +- axum-core/src/extract/mod.rs | 32 ++++++++++++++++++++++++++++++++ axum/CHANGELOG.md | 2 +- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/axum-core/CHANGELOG.md b/axum-core/CHANGELOG.md index 68f4805032..ecf78f313b 100644 --- a/axum-core/CHANGELOG.md +++ b/axum-core/CHANGELOG.md @@ -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) diff --git a/axum-core/src/extract/mod.rs b/axum-core/src/extract/mod.rs index 680234fea7..a1406f5080 100644 --- a/axum-core/src/extract/mod.rs +++ b/axum-core/src/extract/mod.rs @@ -113,6 +113,38 @@ impl RequestParts { } } + /// Apply an extractor to this `RequestParts`. + /// + /// `req.extract::()` 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 FromRequest for MyExtractor { + /// type Rejection = Infallible; + /// + /// async fn from_request(req: &mut RequestParts) -> Result { + /// let method = req.extract::().await?; + /// let path = req.extract::().await?.path().to_owned(); + /// + /// todo!() + /// } + /// } + /// ``` + pub async fn extract>(&mut self) -> Result { + 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 diff --git a/axum/CHANGELOG.md b/axum/CHANGELOG.md index 32db74be0e..8e9bdac1f0 100644 --- a/axum/CHANGELOG.md +++ b/axum/CHANGELOG.md @@ -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)