Skip to main content

vld_web/rama/extract/
query.rs

1use crate::common::query_string_to_json;
2use crate::rama::rejection::VldRejection;
3use rama::http::request::Parts;
4use rama::http::service::web::extract::FromPartsStateRefPair;
5use vld::schema::VldParse;
6
7/// Rama extractor that validates **URL query parameters**.
8///
9/// See [`crate::common::parse_query_string`]: repeated keys and `a[]`
10/// become arrays, values are coerced losslessly (`"42"` → number,
11/// `"true"`/`"false"` → boolean, `?flag` / `?x=` → `""`, `"01234"` stays a
12/// string).
13pub struct VldQuery<T>(pub T);
14
15impl<T, State> FromPartsStateRefPair<State> for VldQuery<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 query_string = parts
27            .uri
28            .query()
29            .map(|q| q.as_encoded_str().into_owned())
30            .unwrap_or_default();
31        let value = query_string_to_json(&query_string);
32        let parsed = crate::common::parse_coerced::<T>(&value).map_err(VldRejection::from_vld)?;
33        Ok(VldQuery(parsed))
34    }
35}