Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OptionalQuery extractor #2310

Merged
merged 5 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions axum-extra/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ and this project adheres to [Semantic Versioning].

# Unreleased

- **added:** `OptionalQuery` extractor ([#2310])
- **added:** `TypedHeader` which used to be in `axum` ([#1850])
- **added:** `Clone` implementation for `ErasedJson` ([#2142])
- **breaking:** Update to prost 0.12. Used for the `Protobuf` extractor
- **breaking:** Make `tokio` an optional dependency

[#1850]: https://github.com/tokio-rs/axum/pull/1850
[#2142]: https://github.com/tokio-rs/axum/pull/2142
[#2310]: https://github.com/tokio-rs/axum/pull/2310

# 0.7.4 (18. April, 2023)

Expand Down
6 changes: 6 additions & 0 deletions axum-extra/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ mod form;
#[cfg(feature = "cookie")]
pub mod cookie;

#[cfg(feature = "query")]
mod optional_query;
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved

#[cfg(feature = "query")]
mod query;

Expand All @@ -30,6 +33,9 @@ pub use self::cookie::SignedCookieJar;
#[cfg(feature = "form")]
pub use self::form::{Form, FormRejection};

#[cfg(feature = "query")]
pub use self::optional_query::{OptionalQuery, OptionalQueryRejection};

#[cfg(feature = "query")]
pub use self::query::{Query, QueryRejection};

Expand Down
189 changes: 189 additions & 0 deletions axum-extra/src/extract/optional_query.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
use axum::{
async_trait,
extract::FromRequestParts,
response::{IntoResponse, Response},
Error,
};
use http::{request::Parts, StatusCode};
use serde::de::DeserializeOwned;
use std::fmt;

/// Extractor that deserializes query strings into `None` if no query parameters are present and `Some(T)` otherwise.
///
/// `T` is expected to implement [`serde::Deserialize`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{routing::get, Router};
/// use axum_extra::extract::OptionalQuery;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Pagination {
/// page: usize,
/// per_page: usize,
/// }
///
/// // This will parse query strings like `?page=2&per_page=30` into `Some(Pagination)` and
/// // empty query string into `None`
/// async fn list_things(OptionalQuery(pagination): OptionalQuery<Pagination>) {
/// match pagination {
/// Some(Pagination{page, per_page}) => { /* return specified page */ },
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
/// None => { /* return fist page */ }
/// }
/// // ...
/// }
///
/// let app = Router::new().route("/list_things", get(list_things));
/// # let _: Router = app;
/// ```
///
/// If the query string cannot be parsed it will reject the request with a `400
/// Bad Request` response.
///
/// For handling values being empty vs missing see the [query-params-with-empty-strings][example]
/// example.
///
/// [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")))]
#[derive(Debug, Clone, Copy, Default)]
pub struct OptionalQuery<T>(pub Option<T>);

#[async_trait]
impl<T, S> FromRequestParts<S> for OptionalQuery<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = OptionalQueryRejection;

async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
if let Some(query) = parts.uri.query() {
let value = serde_html_form::from_str(query).map_err(|err| {
OptionalQueryRejection::FailedToDeserializeQueryString(Error::new(err))
})?;
Ok(OptionalQuery(value))
} else {
Ok(OptionalQuery(None))
}
}
}

impl<T> std::ops::Deref for OptionalQuery<T> {
type Target = Option<T>;

#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}

impl<T> std::ops::DerefMut for OptionalQuery<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

/// Rejection used for [`OptionalQuery`].
///
/// Contains one variant for each way the [`OptionalQuery`] extractor can fail.
#[derive(Debug)]
#[non_exhaustive]
#[cfg(feature = "query")]
pub enum OptionalQueryRejection {
#[allow(missing_docs)]
FailedToDeserializeQueryString(Error),
}

impl IntoResponse for OptionalQueryRejection {
fn into_response(self) -> Response {
match self {
Self::FailedToDeserializeQueryString(inner) => (
StatusCode::BAD_REQUEST,
format!("Failed to deserialize query string: {inner}"),
)
.into_response(),
}
}
}

impl fmt::Display for OptionalQueryRejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FailedToDeserializeQueryString(inner) => inner.fmt(f),
}
}
}

impl std::error::Error for OptionalQueryRejection {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::FailedToDeserializeQueryString(inner) => Some(inner),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::test_helpers::*;
use axum::{routing::post, Router};
use http::{header::CONTENT_TYPE, StatusCode};
use serde::Deserialize;

#[tokio::test]
async fn no_parameters_deserialize_into_none() {
#[derive(Deserialize)]
struct Data {
value: String,
}

let app = Router::new().route(
"/",
post(|OptionalQuery(data): OptionalQuery<Data>| async move {
match data {
None => "None".into(),
Some(data) => data.value,
}
}),
);

let client = TestClient::new(app);

let res = client.post("/").body("").send().await;

assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "None");
}

#[tokio::test]
async fn parsing_errors_are_preserved() {
#[derive(Deserialize)]
struct Data {
value: String,
}

let app = Router::new().route(
"/",
post(|OptionalQuery(data): OptionalQuery<Data>| async move {
match data {
None => "None".into(),
Some(data) => data.value,
}
}),
);

let client = TestClient::new(app);

let res = client
.post("/?other=something")
.header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.body("")
.send()
.await;

assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
}