2022-05-17 20:19:24 +02:00
|
|
|
use axum::{
|
|
|
|
|
async_trait,
|
|
|
|
|
extract::{
|
|
|
|
|
rejection::{FailedToDeserializeQueryString, QueryRejection},
|
2022-08-22 12:23:20 +02:00
|
|
|
FromRequestParts,
|
2022-05-17 20:19:24 +02:00
|
|
|
},
|
|
|
|
|
};
|
2022-08-22 12:23:20 +02:00
|
|
|
use http::request::Parts;
|
2022-05-17 20:19:24 +02:00
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
|
use std::ops::Deref;
|
|
|
|
|
|
|
|
|
|
/// Extractor that deserializes query strings into some type.
|
|
|
|
|
///
|
|
|
|
|
/// `T` is expected to implement [`serde::Deserialize`].
|
|
|
|
|
///
|
2022-07-27 16:32:21 +02:00
|
|
|
/// # Differences from `axum::extract::Query`
|
2022-05-17 20:19:24 +02:00
|
|
|
///
|
|
|
|
|
/// This extractor uses [`serde_html_form`] under-the-hood which supports multi-value items. These
|
|
|
|
|
/// are sent by multiple `<input>` attributes of the same name (e.g. checkboxes) and `<select>`s
|
|
|
|
|
/// with the `multiple` attribute. Those values can be collected into a `Vec` or other sequential
|
|
|
|
|
/// container.
|
|
|
|
|
///
|
|
|
|
|
/// # Example
|
|
|
|
|
///
|
|
|
|
|
/// ```rust,no_run
|
|
|
|
|
/// use axum::{routing::get, Router};
|
|
|
|
|
/// use axum_extra::extract::Query;
|
|
|
|
|
/// use serde::Deserialize;
|
|
|
|
|
///
|
|
|
|
|
/// #[derive(Deserialize)]
|
|
|
|
|
/// struct Pagination {
|
|
|
|
|
/// page: usize,
|
|
|
|
|
/// per_page: usize,
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// // This will parse query strings like `?page=2&per_page=30` into `Pagination`
|
|
|
|
|
/// // structs.
|
|
|
|
|
/// async fn list_things(pagination: Query<Pagination>) {
|
|
|
|
|
/// let pagination: Pagination = pagination.0;
|
|
|
|
|
///
|
|
|
|
|
/// // ...
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let app = Router::new().route("/list_things", get(list_things));
|
|
|
|
|
/// # async {
|
|
|
|
|
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
|
|
|
|
|
/// # };
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// If the query string cannot be parsed it will reject the request with a `422
|
|
|
|
|
/// Unprocessable Entity` 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 Query<T>(pub T);
|
|
|
|
|
|
|
|
|
|
#[async_trait]
|
2022-08-22 12:23:20 +02:00
|
|
|
impl<T, S> FromRequestParts<S> for Query<T>
|
2022-05-17 20:19:24 +02:00
|
|
|
where
|
|
|
|
|
T: DeserializeOwned,
|
2022-08-17 22:08:24 +02:00
|
|
|
S: Send + Sync,
|
2022-05-17 20:19:24 +02:00
|
|
|
{
|
|
|
|
|
type Rejection = QueryRejection;
|
|
|
|
|
|
2022-08-22 12:23:20 +02:00
|
|
|
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
|
|
|
|
let query = parts.uri.query().unwrap_or_default();
|
2022-05-17 20:19:24 +02:00
|
|
|
let value = serde_html_form::from_str(query)
|
2022-07-18 15:43:18 +02:00
|
|
|
.map_err(FailedToDeserializeQueryString::__private_new)?;
|
2022-05-17 20:19:24 +02:00
|
|
|
Ok(Query(value))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Deref for Query<T> {
|
|
|
|
|
type Target = T;
|
|
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
|
&self.0
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[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 supports_multiple_values() {
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
struct Data {
|
|
|
|
|
#[serde(rename = "value")]
|
|
|
|
|
values: Vec<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let app = Router::new().route(
|
|
|
|
|
"/",
|
|
|
|
|
post(|Query(data): Query<Data>| async move { data.values.join(",") }),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let client = TestClient::new(app);
|
|
|
|
|
|
|
|
|
|
let res = client
|
|
|
|
|
.post("/?value=one&value=two")
|
|
|
|
|
.header(CONTENT_TYPE, "application/x-www-form-urlencoded")
|
|
|
|
|
.body("")
|
|
|
|
|
.send()
|
|
|
|
|
.await;
|
|
|
|
|
|
|
|
|
|
assert_eq!(res.status(), StatusCode::OK);
|
|
|
|
|
assert_eq!(res.text().await, "one,two");
|
|
|
|
|
}
|
|
|
|
|
}
|