actix_web_validator/
qsquery.rs

1//! Query extractor (serde_qs based).
2use crate::error::Error;
3use std::ops::Deref;
4use std::sync::Arc;
5use std::{fmt, ops};
6
7use actix_web::{FromRequest, HttpRequest};
8use futures::future::{err, ok, Ready};
9use serde::de;
10use serde_qs::Config as QsConfig;
11use validator::Validate;
12
13type ErrHandler = Arc<dyn Fn(Error, &HttpRequest) -> actix_web::Error + Send + Sync>;
14
15/// Query extractor configuration (serde_qs based).
16///
17/// ```rust
18/// use actix_web::{error, web, App, FromRequest, HttpResponse};
19/// use actix_web_validator::QsQueryConfig;
20/// use serde_qs::actix::QsQuery;
21/// use serde_qs::Config as QsConfig;
22/// use serde::Deserialize;
23///
24/// #[derive(Deserialize)]
25/// struct Info {
26///     username: String,
27/// }
28///
29/// /// deserialize `Info` from request's querystring
30/// async fn index(info: QsQuery<Info>) -> String {
31///     format!("Welcome {}!", info.username)
32/// }
33///
34/// fn main() {
35///     let qs_query_config = QsQueryConfig::default()
36///         .error_handler(|err, req| {  // <- create custom error response
37///             error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into()
38///         })
39///         .qs_config(QsConfig::default());
40///     let app = App::new().service(
41///         web::resource("/index.html").app_data(qs_query_config)
42///             .route(web::post().to(index))
43///     );
44/// }
45/// ```
46#[derive(Default)]
47pub struct QsQueryConfig {
48    ehandler: Option<ErrHandler>,
49    qs_config: QsConfig,
50}
51
52impl QsQueryConfig {
53    /// Set custom error handler
54    pub fn error_handler<F>(mut self, f: F) -> Self
55    where
56        F: Fn(Error, &HttpRequest) -> actix_web::Error + Send + Sync + 'static,
57    {
58        self.ehandler = Some(Arc::new(f));
59        self
60    }
61
62    /// Set custom serialization parameters
63    pub fn qs_config(mut self, config: QsConfig) -> Self {
64        self.qs_config = config;
65        self
66    }
67}
68
69/// Extract and validate typed information from the request's query (serde_qs based).
70///
71/// For query decoding uses [serde_qs](https://docs.rs/serde_qs/latest/serde_qs/) crate
72/// [`QsQueryConfig`] allows to configure extraction process.
73///
74/// ## Example
75///
76/// ```rust
77/// use actix_web::{web, App};
78/// use serde::Deserialize;
79/// use actix_web_validator::QsQuery;
80/// use validator::Validate;
81///
82/// #[derive(Debug, Deserialize)]
83/// pub enum ResponseType {
84///     Token,
85///     Code
86/// }
87///
88/// #[derive(Deserialize, Validate)]
89/// pub struct AuthRequest {
90///     #[validate(range(min = 1000, max = 9999))]
91///     id: u64,
92///     response_type: ResponseType,
93/// }
94///
95/// // Use `Query` extractor for query information (and destructure it within the signature).
96/// // This handler gets called only if the request's query string contains a `id` and
97/// // `response_type` fields.
98/// // The correct request for this handler would be `/index.html?id=1234&response_type=Code"`.
99/// async fn index(info: QsQuery<AuthRequest>) -> String {
100///     format!("Authorization request for client with id={} and type={:?}!", info.id, info.response_type)
101/// }
102///
103/// fn main() {
104///     let app = App::new().service(
105///         web::resource("/index.html").route(web::get().to(index))); // <- use `Query` extractor
106/// }
107/// ```
108#[derive(PartialEq, Eq, PartialOrd, Ord)]
109pub struct QsQuery<T>(pub T);
110
111impl<T> AsRef<T> for QsQuery<T> {
112    fn as_ref(&self) -> &T {
113        &self.0
114    }
115}
116
117impl<T> Deref for QsQuery<T> {
118    type Target = T;
119
120    fn deref(&self) -> &T {
121        &self.0
122    }
123}
124
125impl<T> ops::DerefMut for QsQuery<T> {
126    fn deref_mut(&mut self) -> &mut T {
127        &mut self.0
128    }
129}
130
131impl<T: fmt::Debug> fmt::Debug for QsQuery<T> {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        self.0.fmt(f)
134    }
135}
136
137impl<T: fmt::Display> fmt::Display for QsQuery<T> {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        self.0.fmt(f)
140    }
141}
142
143impl<T> QsQuery<T>
144where
145    T: Validate,
146{
147    /// Deconstruct to an inner value.
148    pub fn into_inner(self) -> T {
149        self.0
150    }
151}
152
153/// Extract typed information from the request's query.
154///
155/// ## Example
156///
157/// ```rust
158/// use actix_web::{web, App};
159/// use serde::Deserialize;
160/// use actix_web_validator::QsQuery;
161/// use validator::Validate;
162///
163/// #[derive(Debug, Deserialize)]
164/// pub enum ResponseType {
165///     Token,
166///     Code
167/// }
168///
169/// #[derive(Deserialize, Validate)]
170/// pub struct AuthRequest {
171///     #[validate(range(min = 1000, max = 9999))]
172///     id: u64,
173///     response_type: ResponseType,
174/// }
175///
176/// // Use `Query` extractor for query information (and destructure it within the signature).
177/// // This handler gets called only if the request's query string contains a `id` and
178/// // `response_type` fields.
179/// // The correct request for this handler would be `/index.html?id=19&response_type=Code"`.
180/// async fn index(QsQuery(info): QsQuery<AuthRequest>) -> String {
181///     format!("Authorization request for client with id={} and type={:?}!", info.id, info.response_type)
182/// }
183///
184/// fn main() {
185///     let app = App::new().service(
186///        web::resource("/index.html").route(web::get().to(index))); // <- use `Query` extractor
187/// }
188/// ```
189impl<T> FromRequest for QsQuery<T>
190where
191    T: de::DeserializeOwned + Validate,
192{
193    type Error = actix_web::Error;
194    type Future = Ready<Result<Self, Self::Error>>;
195
196    /// Builds Query struct from request and provides validation mechanism
197    #[inline]
198    fn from_request(req: &actix_web::HttpRequest, _: &mut actix_web::dev::Payload) -> Self::Future {
199        let query_config = req.app_data::<QsQueryConfig>();
200
201        let error_handler = query_config.map(|c| c.ehandler.clone()).unwrap_or(None);
202
203        let default_qsconfig = QsConfig::default();
204        let qsconfig = query_config
205            .map(|c| &c.qs_config)
206            .unwrap_or(&default_qsconfig);
207
208        qsconfig
209            .deserialize_str::<T>(req.query_string())
210            .map_err(Error::from)
211            .and_then(|value| {
212                value
213                    .validate()
214                    .map(move |_| value)
215                    .map_err(Error::Validate)
216            })
217            .map_err(move |e| {
218                log::debug!(
219                    "Failed during Query extractor validation. \
220                     Request path: {:?}",
221                    req.path()
222                );
223                if let Some(error_handler) = error_handler {
224                    (error_handler)(e, req)
225                } else {
226                    e.into()
227                }
228            })
229            .map(|value| ok(QsQuery(value)))
230            .unwrap_or_else(err)
231    }
232}