salvo_oapi/extract/payload/
form.rs

1use std::fmt::{self, Debug, Display, Formatter};
2use std::ops::{Deref, DerefMut};
3
4use salvo_core::extract::{Extractible, Metadata};
5use salvo_core::{Request, Writer, async_trait};
6use serde::{Deserialize, Deserializer};
7
8use crate::endpoint::EndpointArgRegister;
9use crate::{Components, Content, Operation, RequestBody, ToRequestBody, ToSchema};
10
11/// Represents the parameters passed by the URI path.
12pub struct FormBody<T>(pub T);
13impl<T> FormBody<T> {
14    /// Consumes self and returns the value of the parameter.
15    pub fn into_inner(self) -> T {
16        self.0
17    }
18}
19
20impl<T> Deref for FormBody<T> {
21    type Target = T;
22
23    fn deref(&self) -> &Self::Target {
24        &self.0
25    }
26}
27
28impl<T> DerefMut for FormBody<T> {
29    fn deref_mut(&mut self) -> &mut Self::Target {
30        &mut self.0
31    }
32}
33
34impl<'de, T> ToRequestBody for FormBody<T>
35where
36    T: Deserialize<'de> + ToSchema,
37{
38    fn to_request_body(components: &mut Components) -> RequestBody {
39        RequestBody::new()
40            .description("Extract form format data from request.")
41            .add_content(
42                "application/x-www-form-urlencoded",
43                Content::new(T::to_schema(components)),
44            )
45            .add_content("multipart/*", Content::new(T::to_schema(components)))
46    }
47}
48
49impl<T> fmt::Debug for FormBody<T>
50where
51    T: Debug,
52{
53    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
54        self.0.fmt(f)
55    }
56}
57
58impl<T: Display> Display for FormBody<T> {
59    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
60        self.0.fmt(f)
61    }
62}
63
64impl<'ex, T> Extractible<'ex> for FormBody<T>
65where
66    T: Deserialize<'ex> + Send,
67{
68    fn metadata() -> &'static Metadata {
69        static METADATA: Metadata = Metadata::new("");
70        &METADATA
71    }
72    async fn extract(
73        req: &'ex mut Request,
74    ) -> Result<Self, impl Writer + Send + fmt::Debug + 'static> {
75        req.parse_form().await
76    }
77    async fn extract_with_arg(
78        req: &'ex mut Request,
79        _arg: &str,
80    ) -> Result<Self, impl Writer + Send + fmt::Debug + 'static> {
81        Self::extract(req).await
82    }
83}
84
85impl<'de, T> Deserialize<'de> for FormBody<T>
86where
87    T: Deserialize<'de>,
88{
89    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
90    where
91        D: Deserializer<'de>,
92    {
93        T::deserialize(deserializer).map(FormBody)
94    }
95}
96
97#[async_trait]
98impl<'de, T> EndpointArgRegister for FormBody<T>
99where
100    T: Deserialize<'de> + ToSchema,
101{
102    fn register(components: &mut Components, operation: &mut Operation, _arg: &str) {
103        let request_body = Self::to_request_body(components);
104        let _ = <T as ToSchema>::to_schema(components);
105        operation.request_body = Some(request_body);
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use std::collections::BTreeMap;
112
113    use assert_json_diff::assert_json_eq;
114    use salvo_core::test::TestClient;
115    use serde_json::json;
116
117    use super::*;
118
119    #[test]
120    fn test_form_body_into_inner() {
121        let form = FormBody::<String>("form_body".to_owned());
122        assert_eq!(form.into_inner(), "form_body".to_owned());
123    }
124
125    #[test]
126    fn test_form_body_deref() {
127        let form = FormBody::<String>("form_body".to_owned());
128        assert_eq!(form.deref(), &"form_body".to_owned());
129    }
130
131    #[test]
132    fn test_form_body_deref_mut() {
133        let mut form = FormBody::<String>("form_body".to_owned());
134        assert_eq!(form.deref_mut(), &mut "form_body".to_owned());
135    }
136
137    #[test]
138    fn test_form_body_to_request_body() {
139        let mut components = Components::default();
140        let request_body = FormBody::<String>::to_request_body(&mut components);
141        assert_json_eq!(
142            request_body,
143            json!({
144                "description": "Extract form format data from request.",
145                "content": {
146                    "application/x-www-form-urlencoded": {
147                        "schema": {
148                            "type": "string"
149                        }
150                    },
151                    "multipart/*": {
152                        "schema": {
153                            "type": "string"
154                        }
155                    }
156                }
157            })
158        );
159    }
160
161    #[test]
162    fn test_form_body_debug() {
163        let form = FormBody::<String>("form_body".to_owned());
164        assert_eq!(format!("{form:?}"), r#""form_body""#);
165    }
166
167    #[test]
168    fn test_form_body_display() {
169        let form = FormBody::<String>("form_body".to_owned());
170        assert_eq!(format!("{form}"), "form_body");
171    }
172
173    #[test]
174    fn test_form_body_metadata() {
175        let metadata = FormBody::<String>::metadata();
176        assert_eq!("", metadata.name);
177    }
178
179    #[tokio::test]
180    async fn test_form_body_extract_with_arg() {
181        let map = BTreeMap::from_iter([("key", "value")]);
182        let mut req = TestClient::post("http://127.0.0.1:8698/")
183            .form(&map)
184            .build();
185        let result = FormBody::<BTreeMap<&str, &str>>::extract_with_arg(&mut req, "key").await;
186        assert_eq!("value", result.unwrap().0["key"]);
187    }
188
189    #[test]
190    fn test_form_body_register() {
191        let mut components = Components::new();
192        let mut operation = Operation::new();
193        FormBody::<String>::register(&mut components, &mut operation, "arg");
194
195        assert_json_eq!(
196            operation,
197            json!({
198                "requestBody": {
199                    "content": {
200                        "application/x-www-form-urlencoded": {
201                            "schema": {
202                                "type": "string"
203                            }
204                        },
205                        "multipart/*": {
206                            "schema": {
207                                "type": "string"
208                            }
209                        }
210                    },
211                    "description": "Extract form format data from request."
212                },
213                "responses": {}
214            })
215        );
216    }
217}