Skip to main content

vld_web/rama/extract/
form.rs

1use std::future::Future;
2
3use crate::common::{parse_form_body, require_form_content_type};
4use crate::rama::rejection::VldRejection;
5use rama::http::service::web::extract::{FromRequest, FromRequestBody};
6use rama::http::{Body, Request, header};
7use vld::schema::VldParse;
8
9/// Rama extractor that validates **URL-encoded form bodies**
10/// (`application/x-www-form-urlencoded`, 415 otherwise).
11///
12/// Only the body is read — never the query string, whatever the method
13/// (use [`VldQuery`](crate::rama::VldQuery) for that). Bodies above the
14/// [`VldBodyLimit`](crate::rama::VldBodyLimit) extension (default 2 MiB) are 413.
15pub struct VldForm<T>(pub T);
16
17impl<T> FromRequest for VldForm<T>
18where
19    T: VldParse + Send + Sync + 'static,
20{
21    type Rejection = VldRejection;
22
23    async fn from_request(req: Request) -> Result<Self, Self::Rejection> {
24        let (parts, body) = req.into_parts();
25        Self::from_request_body(&parts, body).await
26    }
27}
28
29impl<T> FromRequestBody for VldForm<T>
30where
31    T: VldParse + Send + Sync + 'static,
32{
33    // Copy needed parts first — future is `'static` (Rama FromRequestBody contract).
34    #[allow(clippy::manual_async_fn)]
35    fn from_request_body(
36        parts: &rama::http::request::Parts,
37        body: Body,
38    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send + 'static {
39        let content_type = require_form_content_type(
40            parts
41                .headers
42                .get(header::CONTENT_TYPE)
43                .and_then(|v| v.to_str().ok()),
44        );
45        let limit = super::body_limit(parts);
46        async move {
47            content_type?;
48            let bytes = super::read_body(body, limit).await?;
49            let value = parse_form_body(&bytes)?;
50            let parsed =
51                crate::common::parse_coerced::<T>(&value).map_err(VldRejection::from_vld)?;
52            Ok(VldForm(parsed))
53        }
54    }
55}