poem_openapi/payload/
form.rs1use std::ops::{Deref, DerefMut};
2
3use poem::{FromRequest, Request, RequestBody, Result};
4use serde::de::DeserializeOwned;
5
6use crate::{
7 error::ParseRequestPayloadError,
8 payload::{ParsePayload, Payload},
9 registry::{MetaSchemaRef, Registry},
10 types::Type,
11};
12
13#[derive(Debug, Clone, Eq, PartialEq)]
15pub struct Form<T>(pub T);
16
17impl<T> Deref for Form<T> {
18 type Target = T;
19
20 fn deref(&self) -> &Self::Target {
21 &self.0
22 }
23}
24
25impl<T> DerefMut for Form<T> {
26 fn deref_mut(&mut self) -> &mut Self::Target {
27 &mut self.0
28 }
29}
30
31impl<T: Type> Payload for Form<T> {
32 const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
33
34 fn check_content_type(content_type: &str) -> bool {
35 matches!(content_type.parse::<mime::Mime>(), Ok(content_type) if content_type.type_() == "application"
36 && (content_type.subtype() == "x-www-form-urlencoded"
37 || content_type
38 .suffix()
39 .is_some_and(|v| v == "x-www-form-urlencoded")))
40 }
41
42 fn schema_ref() -> MetaSchemaRef {
43 T::schema_ref()
44 }
45
46 #[allow(unused_variables)]
47 fn register(registry: &mut Registry) {
48 T::register(registry);
49 }
50}
51
52impl<T: DeserializeOwned> ParsePayload for Form<T> {
53 const IS_REQUIRED: bool = true;
54
55 async fn from_request(req: &Request, body: &mut RequestBody) -> Result<Self> {
56 let data = Vec::<u8>::from_request(req, body).await?;
57 Ok(Self(serde_urlencoded::from_bytes(&data).map_err(
58 |err| ParseRequestPayloadError {
59 reason: err.to_string(),
60 },
61 )?))
62 }
63}
64
65impl_apirequest_for_payload!(Form<T>, T: DeserializeOwned + Type);