Skip to main content

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::{Depot, 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        // Build (and register) the schema once and reuse it for both media types.
40        let schema = T::to_schema(components);
41        RequestBody::new()
42            .description("Extract form format data from request.")
43            .add_content(
44                "application/x-www-form-urlencoded",
45                Content::new(schema.clone()),
46            )
47            // NOTE: `multipart/*` is not a strictly valid OpenAPI media-type key, but
48            // keeping it distinct from `multipart/form-data` avoids clobbering the
49            // file schema that `FormFile`/`FormFiles` register under
50            // `multipart/form-data` when both are used on the same endpoint. Properly
51            // emitting `multipart/form-data` requires merging the form and file
52            // schemas; left as follow-up.
53            .add_content("multipart/*", Content::new(schema))
54    }
55}
56
57impl<T> fmt::Debug for FormBody<T>
58where
59    T: Debug,
60{
61    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62        self.0.fmt(f)
63    }
64}
65
66impl<T: Display> Display for FormBody<T> {
67    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
68        self.0.fmt(f)
69    }
70}
71
72impl<'ex, T> Extractible<'ex> for FormBody<T>
73where
74    T: Deserialize<'ex> + Send,
75{
76    fn metadata() -> &'static Metadata {
77        static METADATA: Metadata = Metadata::new("");
78        &METADATA
79    }
80    async fn extract(
81        req: &'ex mut Request,
82        _depot: &'ex mut Depot,
83    ) -> Result<Self, impl Writer + Send + fmt::Debug + 'static> {
84        req.parse_form().await
85    }
86    async fn extract_with_arg(
87        req: &'ex mut Request,
88        depot: &'ex mut Depot,
89        _arg: &str,
90    ) -> Result<Self, impl Writer + Send + fmt::Debug + 'static> {
91        Self::extract(req, depot).await
92    }
93}
94
95impl<'de, T> Deserialize<'de> for FormBody<T>
96where
97    T: Deserialize<'de>,
98{
99    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
100    where
101        D: Deserializer<'de>,
102    {
103        T::deserialize(deserializer).map(FormBody)
104    }
105}
106
107#[async_trait]
108impl<'de, T> EndpointArgRegister for FormBody<T>
109where
110    T: Deserialize<'de> + ToSchema,
111{
112    fn register(components: &mut Components, operation: &mut Operation, _arg: &str) {
113        // `to_request_body` already builds and registers the schema; no extra
114        // `to_schema` call is needed here.
115        let request_body = Self::to_request_body(components);
116        operation.request_body = Some(request_body);
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use std::collections::BTreeMap;
123
124    use assert_json_diff::assert_json_eq;
125    use salvo_core::test::TestClient;
126    use serde_json::json;
127
128    use super::*;
129
130    #[test]
131    fn test_form_body_into_inner() {
132        let form = FormBody::<String>("form_body".to_owned());
133        assert_eq!(form.into_inner(), "form_body".to_owned());
134    }
135
136    #[test]
137    fn test_form_body_deref() {
138        let form = FormBody::<String>("form_body".to_owned());
139        assert_eq!(form.deref(), &"form_body".to_owned());
140    }
141
142    #[test]
143    fn test_form_body_deref_mut() {
144        let mut form = FormBody::<String>("form_body".to_owned());
145        assert_eq!(form.deref_mut(), &mut "form_body".to_owned());
146    }
147
148    #[test]
149    fn test_form_body_to_request_body() {
150        let mut components = Components::default();
151        let request_body = FormBody::<String>::to_request_body(&mut components);
152        assert_json_eq!(
153            request_body,
154            json!({
155                "description": "Extract form format data from request.",
156                "content": {
157                    "application/x-www-form-urlencoded": {
158                        "schema": {
159                            "type": "string"
160                        }
161                    },
162                    "multipart/*": {
163                        "schema": {
164                            "type": "string"
165                        }
166                    }
167                }
168            })
169        );
170    }
171
172    #[test]
173    fn test_form_body_debug() {
174        let form = FormBody::<String>("form_body".to_owned());
175        assert_eq!(format!("{form:?}"), r#""form_body""#);
176    }
177
178    #[test]
179    fn test_form_body_display() {
180        let form = FormBody::<String>("form_body".to_owned());
181        assert_eq!(format!("{form}"), "form_body");
182    }
183
184    #[test]
185    fn test_form_body_metadata() {
186        let metadata = FormBody::<String>::metadata();
187        assert_eq!("", metadata.name);
188    }
189
190    #[tokio::test]
191    async fn test_form_body_extract_with_arg() {
192        let map = BTreeMap::from_iter([("key", "value")]);
193        let mut req = TestClient::post("http://127.0.0.1:8698/")
194            .form(&map)
195            .build();
196        let mut depot = Depot::new();
197        let result =
198            FormBody::<BTreeMap<&str, &str>>::extract_with_arg(&mut req, &mut depot, "key").await;
199        assert_eq!("value", result.unwrap().0["key"]);
200    }
201
202    #[test]
203    fn test_form_body_register() {
204        let mut components = Components::new();
205        let mut operation = Operation::new();
206        FormBody::<String>::register(&mut components, &mut operation, "arg");
207
208        assert_json_eq!(
209            operation,
210            json!({
211                "requestBody": {
212                    "content": {
213                        "application/x-www-form-urlencoded": {
214                            "schema": {
215                                "type": "string"
216                            }
217                        },
218                        "multipart/*": {
219                            "schema": {
220                                "type": "string"
221                            }
222                        }
223                    },
224                    "description": "Extract form format data from request."
225                },
226                "responses": {}
227            })
228        );
229    }
230}