From 4b215e08395e8931ed771bd7a8ef959353610853 Mon Sep 17 00:00:00 2001 From: Miles Granger Date: Fri, 17 May 2019 22:10:46 +0200 Subject: [PATCH] Support Query::from_query() (#846) --- CHANGES.md | 1 + src/types/query.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 2e41312ad..611dd0c54 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,7 @@ ### Add +* Add `Query::from_query()` to extract parameters from a query string. #846 * `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors. ### Changes diff --git a/src/types/query.rs b/src/types/query.rs index 7a91c4215..2c07edfbd 100644 --- a/src/types/query.rs +++ b/src/types/query.rs @@ -52,6 +52,16 @@ impl Query { pub fn into_inner(self) -> T { self.0 } + + /// Get query parameters from the path + pub fn from_query(query_str: &str) -> Result + where + T: de::DeserializeOwned, + { + serde_urlencoded::from_str::(query_str) + .map(|val| Ok(Query(val))) + .unwrap_or_else(move |e| Err(QueryPayloadError::Deserialize(e))) + } } impl ops::Deref for Query { @@ -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::::from_query(&req.query_string()).is_err()); + + let req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); + let mut s = Query::::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();