salvo_oapi/extract/parameter/
path.rs1use std::fmt::{self, Debug, Formatter};
2use std::ops::{Deref, DerefMut};
3
4use salvo_core::Depot;
5use salvo_core::extract::{Extractible, Metadata};
6use salvo_core::http::{ParseError, Request};
7use serde::{Deserialize, Deserializer};
8
9use crate::endpoint::EndpointArgRegister;
10use crate::{Components, Operation, Parameter, ParameterIn, ToSchema};
11
12pub struct PathParam<T>(pub T);
14impl<T> PathParam<T> {
15 pub fn into_inner(self) -> T {
17 self.0
18 }
19}
20
21impl<T> Deref for PathParam<T> {
22 type Target = T;
23
24 fn deref(&self) -> &Self::Target {
25 &self.0
26 }
27}
28
29impl<T> DerefMut for PathParam<T> {
30 fn deref_mut(&mut self) -> &mut Self::Target {
31 &mut self.0
32 }
33}
34
35impl<'de, T> Deserialize<'de> for PathParam<T>
36where
37 T: Deserialize<'de>,
38{
39 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
40 where
41 D: Deserializer<'de>,
42 {
43 T::deserialize(deserializer).map(|value| Self(value))
44 }
45}
46
47impl<T> fmt::Debug for PathParam<T>
48where
49 T: Debug,
50{
51 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
52 self.0.fmt(f)
53 }
54}
55
56impl<T> fmt::Display for PathParam<T>
57where
58 T: fmt::Display,
59{
60 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
61 self.0.fmt(f)
62 }
63}
64
65impl<'ex, T> Extractible<'ex> for PathParam<T>
66where
67 T: Deserialize<'ex>,
68{
69 fn metadata() -> &'static Metadata {
70 static METADATA: Metadata = Metadata::new("");
71 &METADATA
72 }
73 #[allow(refining_impl_trait)]
74 async fn extract(_req: &'ex mut Request, _depot: &'ex mut Depot) -> Result<Self, ParseError> {
75 unimplemented!("path parameter can not be extracted from request")
76 }
77 #[allow(refining_impl_trait)]
78 async fn extract_with_arg(
79 req: &'ex mut Request,
80 _depot: &'ex mut Depot,
81 arg: &str,
82 ) -> Result<Self, ParseError> {
83 let value = req.param(arg).ok_or_else(|| {
84 ParseError::other(format!(
85 "path parameter {arg} not found or convert to type failed"
86 ))
87 })?;
88 Ok(Self(value))
89 }
90}
91
92impl<T> EndpointArgRegister for PathParam<T>
93where
94 T: ToSchema,
95{
96 fn register(components: &mut Components, operation: &mut Operation, arg: &str) {
97 let parameter = Parameter::new(arg)
98 .parameter_in(ParameterIn::Path)
99 .description(format!("Get parameter `{arg}` from request url path."))
100 .schema(T::to_schema(components))
101 .required(true);
102 operation.parameters.insert(parameter);
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use assert_json_diff::assert_json_eq;
109 use salvo_core::test::TestClient;
110 use serde_json::json;
111
112 use super::*;
113
114 #[test]
115 fn test_path_param_into_inner() {
116 let param = PathParam::<String>("param".to_owned());
117 assert_eq!("param".to_owned(), param.into_inner());
118 }
119
120 #[test]
121 fn test_path_param_deref() {
122 let param = PathParam::<String>("param".to_owned());
123 assert_eq!(&"param".to_owned(), param.deref())
124 }
125
126 #[test]
127 fn test_path_param_deref_mut() {
128 let mut param = PathParam::<String>("param".to_owned());
129 assert_eq!(&mut "param".to_owned(), param.deref_mut())
130 }
131
132 #[test]
133 fn test_path_param_deserialize() {
134 let param = serde_json::from_str::<PathParam<String>>(r#""param""#).unwrap();
135 assert_eq!(param.0, "param");
136 }
137
138 #[test]
139 fn test_path_param_debug() {
140 let param = PathParam::<String>("param".to_owned());
141 assert_eq!(format!("{param:?}"), r#""param""#);
142 }
143
144 #[test]
145 fn test_path_param_display() {
146 let param = PathParam::<String>("param".to_owned());
147 assert_eq!(format!("{param}"), "param");
148 }
149
150 #[test]
151 fn test_path_param_metadata() {
152 let metadata = PathParam::<String>::metadata();
153 assert_eq!("", metadata.name);
154 }
155
156 #[tokio::test]
157 #[should_panic]
158 async fn test_path_prarm_extract() {
159 let mut req = Request::new();
160 let mut depot = Depot::new();
161 let _ = PathParam::<String>::extract(&mut req, &mut depot).await;
162 }
163
164 #[tokio::test]
165 async fn test_path_prarm_extract_with_value() {
166 let req = TestClient::get("http://127.0.0.1:5801").build_hyper();
167 let schema = req.uri().scheme().cloned().unwrap();
168 let mut req = Request::from_hyper(req, schema);
169 let mut depot = Depot::new();
170 req.params_mut().insert("param", "param".to_owned());
171 let result = PathParam::<String>::extract_with_arg(&mut req, &mut depot, "param").await;
172 assert_eq!(result.unwrap().0, "param");
173 }
174
175 #[tokio::test]
176 #[should_panic]
177 async fn test_path_prarm_extract_with_value_panic() {
178 let req = TestClient::get("http://127.0.0.1:5801").build_hyper();
179 let schema = req.uri().scheme().cloned().unwrap();
180 let mut req = Request::from_hyper(req, schema);
181 let mut depot = Depot::new();
182 let result = PathParam::<String>::extract_with_arg(&mut req, &mut depot, "param").await;
183 assert_eq!(result.unwrap().0, "param");
184 }
185
186 #[test]
187 fn test_path_param_register() {
188 let mut components = Components::new();
189 let mut operation = Operation::new();
190 PathParam::<String>::register(&mut components, &mut operation, "arg");
191
192 assert_json_eq!(
193 operation,
194 json!({
195 "parameters": [
196 {
197 "name": "arg",
198 "in": "path",
199 "description": "Get parameter `arg` from request url path.",
200 "required": true,
201 "schema": {
202 "type": "string"
203 }
204 }
205 ],
206 "responses": {}
207 })
208 )
209 }
210}