Skip to main content

capy_validation/
lib.rs

1//! JSON form requests backed by the `validator` crate.
2
3use axum::{
4    extract::{FromRequest, Request},
5    Json,
6};
7use capy_core::{AppError, ValidationErrors};
8use serde::de::DeserializeOwned;
9pub use validator::Validate;
10use validator::ValidationErrorsKind;
11
12/// Deserialize and validate a JSON body before invoking the handler.
13/// Put this extractor last, since it consumes the request body.
14#[derive(Debug, Clone)]
15pub struct Validated<T>(pub T);
16
17impl<S, T> FromRequest<S> for Validated<T>
18where
19    S: Send + Sync,
20    T: DeserializeOwned + Validate,
21{
22    type Rejection = AppError;
23
24    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
25        let Json(value) = Json::<T>::from_request(req, state)
26            .await
27            .map_err(AppError::from_json_rejection)?;
28        value.validate().map_err(|errors| {
29            let mut messages = ValidationErrors::new();
30            flatten("", &errors, &mut messages);
31            AppError::Validation(messages)
32        })?;
33        Ok(Self(value))
34    }
35}
36
37fn flatten(prefix: &str, errors: &validator::ValidationErrors, messages: &mut ValidationErrors) {
38    for (field, kind) in errors.errors() {
39        let path = if prefix.is_empty() {
40            field.to_string()
41        } else {
42            format!("{prefix}.{field}")
43        };
44        match kind {
45            ValidationErrorsKind::Field(errors) => {
46                messages.insert(
47                    path.clone(),
48                    errors
49                        .iter()
50                        .map(|error| {
51                            error
52                                .message
53                                .as_ref()
54                                .map(|message| message.to_string())
55                                .unwrap_or_else(|| match error.code.as_ref() {
56                                    "email" => {
57                                        format!("The {path} field must be a valid email address.")
58                                    }
59                                    "length" => format!("The {path} field has an invalid length."),
60                                    "range" => {
61                                        format!("The {path} field is outside the allowed range.")
62                                    }
63                                    "url" => format!("The {path} field must be a valid URL."),
64                                    _ => format!("The {path} field is invalid."),
65                                })
66                        })
67                        .collect(),
68                );
69            }
70            ValidationErrorsKind::Struct(errors) => flatten(&path, errors, messages),
71            ValidationErrorsKind::List(items) => {
72                for (index, errors) in items {
73                    flatten(&format!("{path}.{index}"), errors, messages);
74                }
75            }
76        }
77    }
78}