salvo_oapi/extract/parameter/
query.rs

1use std::fmt::{self, Debug, Display, Formatter};
2use std::ops::{Deref, DerefMut};
3
4use salvo_core::Request;
5use salvo_core::extract::{Extractible, Metadata};
6use salvo_core::http::ParseError;
7use serde::{Deserialize, Deserializer};
8
9use crate::endpoint::EndpointArgRegister;
10use crate::{Components, Operation, Parameter, ParameterIn, ToSchema};
11
12/// Represents the parameters passed by the URI path.
13pub struct QueryParam<T, const REQUIRED: bool = true>(Option<T>);
14impl<T> QueryParam<T, true> {
15    /// Consumes self and returns the value of the parameter.
16    pub fn into_inner(self) -> T {
17        self.0.expect("`QueryParam<T, true>` into_inner get `None`")
18    }
19}
20impl<T> QueryParam<T, false> {
21    /// Consumes self and returns the value of the parameter.
22    pub fn into_inner(self) -> Option<T> {
23        self.0
24    }
25}
26
27impl<T> Deref for QueryParam<T, true> {
28    type Target = T;
29
30    fn deref(&self) -> &Self::Target {
31        self.0
32            .as_ref()
33            .expect("`QueryParam<T, true>` defref get `None`")
34    }
35}
36impl<T> Deref for QueryParam<T, false> {
37    type Target = Option<T>;
38
39    fn deref(&self) -> &Self::Target {
40        &self.0
41    }
42}
43
44impl<T> DerefMut for QueryParam<T, true> {
45    fn deref_mut(&mut self) -> &mut Self::Target {
46        self.0
47            .as_mut()
48            .expect("`QueryParam<T, true>` defref_mut get `None`")
49    }
50}
51impl<T> DerefMut for QueryParam<T, false> {
52    fn deref_mut(&mut self) -> &mut Self::Target {
53        &mut self.0
54    }
55}
56
57impl<'de, T, const R: bool> Deserialize<'de> for QueryParam<T, R>
58where
59    T: Deserialize<'de>,
60{
61    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
62    where
63        D: Deserializer<'de>,
64    {
65        T::deserialize(deserializer).map(|value| QueryParam(Some(value)))
66    }
67}
68
69impl<T: Debug, const R: bool> Debug for QueryParam<T, R> {
70    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
71        self.0.fmt(f)
72    }
73}
74
75impl<T: Display> Display for QueryParam<T, true> {
76    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
77        self.0
78            .as_ref()
79            .expect("`QueryParam<T, true>` as_ref get `None`")
80            .fmt(f)
81    }
82}
83
84impl<'ex, T> Extractible<'ex> for QueryParam<T, true>
85where
86    T: Deserialize<'ex>,
87{
88    fn metadata() -> &'ex Metadata {
89        static METADATA: Metadata = Metadata::new("");
90        &METADATA
91    }
92    #[allow(refining_impl_trait)]
93    async fn extract(_req: &'ex mut Request) -> Result<Self, ParseError> {
94        panic!("query parameter can not be extracted from request")
95    }
96    #[allow(refining_impl_trait)]
97    async fn extract_with_arg(req: &'ex mut Request, arg: &str) -> Result<Self, ParseError> {
98        let value = req.query(arg).ok_or_else(|| {
99            ParseError::other(format!(
100                "query parameter {} not found or convert to type failed",
101                arg
102            ))
103        })?;
104        Ok(Self(value))
105    }
106}
107impl<'ex, T> Extractible<'ex> for QueryParam<T, false>
108where
109    T: Deserialize<'ex>,
110{
111    fn metadata() -> &'ex Metadata {
112        static METADATA: Metadata = Metadata::new("");
113        &METADATA
114    }
115    #[allow(refining_impl_trait)]
116    async fn extract(_req: &'ex mut Request) -> Result<Self, ParseError> {
117        panic!("query parameter can not be extracted from request")
118    }
119    #[allow(refining_impl_trait)]
120    async fn extract_with_arg(req: &'ex mut Request, arg: &str) -> Result<Self, ParseError> {
121        Ok(Self(req.query(arg)))
122    }
123}
124
125impl<T, const R: bool> EndpointArgRegister for QueryParam<T, R>
126where
127    T: ToSchema,
128{
129    fn register(components: &mut Components, operation: &mut Operation, arg: &str) {
130        let parameter = Parameter::new(arg)
131            .parameter_in(ParameterIn::Query)
132            .description(format!("Get parameter `{arg}` from request url query."))
133            .schema(T::to_schema(components))
134            .required(R);
135        operation.parameters.insert(parameter);
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use assert_json_diff::assert_json_eq;
142    use salvo_core::test::TestClient;
143    use serde_json::json;
144
145    use super::*;
146
147    #[test]
148    fn test_required_query_param_into_inner() {
149        let param = QueryParam::<String, true>(Some("param".to_string()));
150        assert_eq!("param".to_string(), param.into_inner());
151    }
152
153    #[test]
154    fn test_required_query_param_deref() {
155        let param = QueryParam::<String, true>(Some("param".to_string()));
156        assert_eq!(&"param".to_string(), param.deref())
157    }
158
159    #[test]
160    fn test_required_query_param_deref_mut() {
161        let mut param = QueryParam::<String, true>(Some("param".to_string()));
162        assert_eq!(&mut "param".to_string(), param.deref_mut())
163    }
164
165    #[test]
166    fn test_query_param_into_inner() {
167        let param = QueryParam::<String, false>(Some("param".to_string()));
168        assert_eq!(Some("param".to_string()), param.into_inner());
169    }
170
171    #[test]
172    fn test_query_param_deref() {
173        let param = QueryParam::<String, false>(Some("param".to_string()));
174        assert_eq!(&Some("param".to_string()), param.deref())
175    }
176
177    #[test]
178    fn test_query_param_deref_mut() {
179        let mut param = QueryParam::<String, false>(Some("param".to_string()));
180        assert_eq!(&mut Some("param".to_string()), param.deref_mut())
181    }
182
183    #[test]
184    fn test_query_param_deserialize() {
185        let param = serde_json::from_str::<QueryParam<String, true>>(r#""param""#).unwrap();
186        assert_eq!(param.0.unwrap(), "param");
187    }
188
189    #[test]
190    fn test_query_param_debug() {
191        let param = QueryParam::<String, true>(Some("param".to_string()));
192        assert_eq!(format!("{:?}", param), r#"Some("param")"#);
193    }
194
195    #[test]
196    fn test_query_param_display() {
197        let param = QueryParam::<String, true>(Some("param".to_string()));
198        assert_eq!(format!("{}", param), "param");
199    }
200
201    #[test]
202    fn test_required_query_param_metadata() {
203        let metadata = QueryParam::<String, true>::metadata();
204        assert_eq!("", metadata.name);
205    }
206
207    #[tokio::test]
208    #[should_panic]
209    async fn test_required_query_prarm_extract() {
210        let mut req = Request::new();
211        let _ = QueryParam::<String, true>::extract(&mut req).await;
212    }
213
214    #[tokio::test]
215    async fn test_required_query_prarm_extract_with_value() {
216        let req = TestClient::get("http://127.0.0.1:5801").build_hyper();
217        let schema = req.uri().scheme().cloned().unwrap();
218        let mut req = Request::from_hyper(req, schema);
219        req.queries_mut()
220            .insert("param".to_string(), "param".to_string());
221        let result = QueryParam::<String, true>::extract_with_arg(&mut req, "param").await;
222        assert_eq!(result.unwrap().0.unwrap(), "param");
223    }
224
225    #[tokio::test]
226    #[should_panic]
227    async fn test_required_query_prarm_extract_with_value_panic() {
228        let req = TestClient::get("http://127.0.0.1:5801").build_hyper();
229        let schema = req.uri().scheme().cloned().unwrap();
230        let mut req = Request::from_hyper(req, schema);
231        let result = QueryParam::<String, true>::extract_with_arg(&mut req, "param").await;
232        assert_eq!(result.unwrap().0.unwrap(), "param");
233    }
234
235    #[test]
236    fn test_query_param_metadata() {
237        let metadata = QueryParam::<String, false>::metadata();
238        assert_eq!("", metadata.name);
239    }
240
241    #[tokio::test]
242    #[should_panic]
243    async fn test_query_prarm_extract() {
244        let mut req = Request::new();
245        let _ = QueryParam::<String, false>::extract(&mut req).await;
246    }
247
248    #[tokio::test]
249    async fn test_query_prarm_extract_with_value() {
250        let req = TestClient::get("http://127.0.0.1:5801").build_hyper();
251        let schema = req.uri().scheme().cloned().unwrap();
252        let mut req = Request::from_hyper(req, schema);
253        req.queries_mut()
254            .insert("param".to_string(), "param".to_string());
255        let result = QueryParam::<String, false>::extract_with_arg(&mut req, "param").await;
256        assert_eq!(result.unwrap().0.unwrap(), "param");
257    }
258
259    #[tokio::test]
260    #[should_panic]
261    async fn test_query_prarm_extract_with_value_panic() {
262        let req = TestClient::get("http://127.0.0.1:5801").build_hyper();
263        let schema = req.uri().scheme().cloned().unwrap();
264        let mut req = Request::from_hyper(req, schema);
265        let result = QueryParam::<String, false>::extract_with_arg(&mut req, "param").await;
266        assert_eq!(result.unwrap().0.unwrap(), "param");
267    }
268
269    #[test]
270    fn test_query_param_register() {
271        let mut components = Components::new();
272        let mut operation = Operation::new();
273        QueryParam::<String, false>::register(&mut components, &mut operation, "arg");
274
275        assert_json_eq!(
276            operation,
277            json!({
278                "parameters": [
279                    {
280                        "name": "arg",
281                        "in": "query",
282                        "description": "Get parameter `arg` from request url query.",
283                        "required": false,
284                        "schema": {
285                            "type": "string"
286                        }
287                    }
288                ],
289                "responses": {}
290            })
291        )
292    }
293}