Skip to main content

vld_web/rama/extract/
path.rs

1use crate::common::path_params_to_json;
2use crate::rama::rejection::VldRejection;
3use rama::http::matcher::UriParams;
4use rama::http::request::Parts;
5use rama::http::service::web::extract::FromPartsStateRefPair;
6use vld::schema::VldParse;
7
8/// Rama extractor that validates **URL path parameters**.
9///
10/// Path segment values are coerced the same way as query parameters. On a
11/// route without parameters the input is an empty object, so a schema whose
12/// fields are all optional still matches.
13pub struct VldPath<T>(pub T);
14
15impl<T, State> FromPartsStateRefPair<State> for VldPath<T>
16where
17    T: VldParse + Send + Sync + 'static,
18    State: Send + Sync + 'static,
19{
20    type Rejection = VldRejection;
21
22    async fn from_parts_state_ref_pair(
23        parts: &Parts,
24        _state: &State,
25    ) -> Result<Self, Self::Rejection> {
26        let value = parts
27            .extensions
28            .get_ref::<UriParams>()
29            .map_or_else(|| serde_json::json!({}), |p| path_params_to_json(p.iter()));
30        let parsed = crate::common::parse_coerced::<T>(&value).map_err(VldRejection::from_vld)?;
31        Ok(VldPath(parsed))
32    }
33}