1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

Support Query<T>::from_query() (#846)

This commit is contained in:
Miles Granger 2019-05-17 22:10:46 +02:00 committed by Nikolay Kim
parent e1ff3bf8fa
commit 4b215e0839
2 changed files with 27 additions and 0 deletions

View File

@ -4,6 +4,7 @@
### Add
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
* `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors.
### Changes

View File

@ -52,6 +52,16 @@ impl<T> Query<T> {
pub fn into_inner(self) -> T {
self.0
}
/// Get query parameters from the path
pub fn from_query(query_str: &str) -> Result<Self, QueryPayloadError>
where
T: de::DeserializeOwned,
{
serde_urlencoded::from_str::<T>(query_str)
.map(|val| Ok(Query(val)))
.unwrap_or_else(move |e| Err(QueryPayloadError::Deserialize(e)))
}
}
impl<T> ops::Deref for Query<T> {
@ -218,6 +228,22 @@ mod tests {
id: String,
}
#[test]
fn test_service_request_extract() {
let req = TestRequest::with_uri("/name/user1/").to_srv_request();
assert!(Query::<Id>::from_query(&req.query_string()).is_err());
let req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
let mut s = Query::<Id>::from_query(&req.query_string()).unwrap();
assert_eq!(s.id, "test");
assert_eq!(format!("{}, {:?}", s, s), "test, Id { id: \"test\" }");
s.id = "test1".to_string();
let s = s.into_inner();
assert_eq!(s.id, "test1");
}
#[test]
fn test_request_extract() {
let req = TestRequest::with_uri("/name/user1/").to_srv_request();