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