Skip to content

Commit

Permalink
Implement OptionalFromRequestParts for axum-extra's Query<T>
Browse files Browse the repository at this point in the history
… and deprecate OptionalQuery.
  • Loading branch information
jplatte committed Nov 26, 2024
1 parent 42bcd63 commit 6460d88
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
5 changes: 4 additions & 1 deletion axum-extra/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,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;
Expand Down
28 changes: 27 additions & 1 deletion axum-extra/src/extract/query.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use axum::{
extract::FromRequestParts,
extract::{FromRequestParts, OptionalFromRequestParts},
response::{IntoResponse, Response},
Error,
};
Expand Down Expand Up @@ -96,6 +96,27 @@ where
}
}

impl<T, S> OptionalFromRequestParts<S> for Query<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = QueryRejection;

async fn from_request_parts(
parts: &mut Parts,
_state: &S,
) -> Result<Option<Self>, 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`].
Expand Down Expand Up @@ -182,9 +203,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<Query<_>> instead"]
#[derive(Debug, Clone, Copy, Default)]
pub struct OptionalQuery<T>(pub Option<T>);

#[allow(deprecated)]
impl<T, S> FromRequestParts<S> for OptionalQuery<T>
where
T: DeserializeOwned,
Expand All @@ -204,6 +227,7 @@ where
}
}

#[allow(deprecated)]
impl<T> std::ops::Deref for OptionalQuery<T> {
type Target = Option<T>;

Expand All @@ -213,6 +237,7 @@ impl<T> std::ops::Deref for OptionalQuery<T> {
}
}

#[allow(deprecated)]
impl<T> std::ops::DerefMut for OptionalQuery<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
Expand Down Expand Up @@ -260,6 +285,7 @@ impl std::error::Error for OptionalQueryRejection {
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
use super::*;
use crate::test_helpers::*;
Expand Down

0 comments on commit 6460d88

Please sign in to comment.