From 91fabd2d9fdf74ba6312c7b6f26feae113092a43 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 30 Dec 2023 23:09:04 +0100 Subject: [PATCH] Implement OptionalFromRequestParts for axum-extra's Query MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit … and deprecate OptionalQuery. --- axum-extra/src/extract/mod.rs | 5 ++++- axum-extra/src/extract/query.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/axum-extra/src/extract/mod.rs b/axum-extra/src/extract/mod.rs index 2b0040fc9f5..5eda5287d07 100644 --- a/axum-extra/src/extract/mod.rs +++ b/axum-extra/src/extract/mod.rs @@ -36,7 +36,10 @@ pub use self::cookie::SignedCookieJar; pub use self::form::{Form, FormRejection}; #[cfg(feature = "query")] -pub use self::query::{OptionalQuery, OptionalQueryRejection, Query, QueryRejection}; +#[allow(deprecated)] +pub use self::query::OptionalQuery; +#[cfg(feature = "query")] +pub use self::query::{OptionalQueryRejection, Query, QueryRejection}; #[cfg(feature = "multipart")] pub use self::multipart::Multipart; diff --git a/axum-extra/src/extract/query.rs b/axum-extra/src/extract/query.rs index 64ccae5ba05..428773a76bd 100644 --- a/axum-extra/src/extract/query.rs +++ b/axum-extra/src/extract/query.rs @@ -1,6 +1,6 @@ use axum::{ async_trait, - extract::FromRequestParts, + extract::{FromRequestParts, OptionalFromRequestParts}, response::{IntoResponse, Response}, Error, }; @@ -71,6 +71,28 @@ where } } +#[async_trait] +impl OptionalFromRequestParts for Query +where + T: DeserializeOwned, + S: Send + Sync, +{ + type Rejection = QueryRejection; + + async fn from_request_parts( + parts: &mut Parts, + _state: &S, + ) -> Result, Self::Rejection> { + if let Some(query) = parts.uri.query() { + let value = serde_html_form::from_str(query) + .map_err(|err| QueryRejection::FailedToDeserializeQueryString(Error::new(err)))?; + Ok(Some(Self(value))) + } else { + Ok(None) + } + } +} + axum_core::__impl_deref!(Query); /// Rejection used for [`Query`]. @@ -152,9 +174,11 @@ impl std::error::Error for QueryRejection { /// /// [example]: https://github.com/tokio-rs/axum/blob/main/examples/query-params-with-empty-strings/src/main.rs #[cfg_attr(docsrs, doc(cfg(feature = "query")))] +#[deprecated = "Use Option> instead"] #[derive(Debug, Clone, Copy, Default)] pub struct OptionalQuery(pub Option); +#[allow(deprecated)] #[async_trait] impl FromRequestParts for OptionalQuery where @@ -175,6 +199,7 @@ where } } +#[allow(deprecated)] impl std::ops::Deref for OptionalQuery { type Target = Option; @@ -184,6 +209,7 @@ impl std::ops::Deref for OptionalQuery { } } +#[allow(deprecated)] impl std::ops::DerefMut for OptionalQuery { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { @@ -231,6 +257,7 @@ impl std::error::Error for OptionalQueryRejection { } #[cfg(test)] +#[allow(deprecated)] mod tests { use super::*; use crate::test_helpers::*;