capy-validation 0.4.0

Validated JSON requests for Capy applications.
Documentation
//! JSON form requests backed by the `validator` crate.

use axum::{
    extract::{FromRequest, Request},
    Json,
};
use capy_core::{AppError, ValidationErrors};
use serde::de::DeserializeOwned;
pub use validator::Validate;
use validator::ValidationErrorsKind;

/// Deserialize and validate a JSON body before invoking the handler.
/// Put this extractor last, since it consumes the request body.
#[derive(Debug, Clone)]
pub struct Validated<T>(pub T);

impl<S, T> FromRequest<S> for Validated<T>
where
    S: Send + Sync,
    T: DeserializeOwned + Validate,
{
    type Rejection = AppError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let Json(value) = Json::<T>::from_request(req, state)
            .await
            .map_err(AppError::from_json_rejection)?;
        value.validate().map_err(|errors| {
            let mut messages = ValidationErrors::new();
            flatten("", &errors, &mut messages);
            AppError::Validation(messages)
        })?;
        Ok(Self(value))
    }
}

fn flatten(prefix: &str, errors: &validator::ValidationErrors, messages: &mut ValidationErrors) {
    for (field, kind) in errors.errors() {
        let path = if prefix.is_empty() {
            field.to_string()
        } else {
            format!("{prefix}.{field}")
        };
        match kind {
            ValidationErrorsKind::Field(errors) => {
                messages.insert(
                    path.clone(),
                    errors
                        .iter()
                        .map(|error| {
                            error
                                .message
                                .as_ref()
                                .map(|message| message.to_string())
                                .unwrap_or_else(|| match error.code.as_ref() {
                                    "email" => {
                                        format!("The {path} field must be a valid email address.")
                                    }
                                    "length" => format!("The {path} field has an invalid length."),
                                    "range" => {
                                        format!("The {path} field is outside the allowed range.")
                                    }
                                    "url" => format!("The {path} field must be a valid URL."),
                                    _ => format!("The {path} field is invalid."),
                                })
                        })
                        .collect(),
                );
            }
            ValidationErrorsKind::Struct(errors) => flatten(&path, errors, messages),
            ValidationErrorsKind::List(items) => {
                for (index, errors) in items {
                    flatten(&format!("{path}.{index}"), errors, messages);
                }
            }
        }
    }
}