ript 0.1.3

Rust implementation of the InertiaJS protocol compatible with `riptc` for generating strong TypeScript bindings.
Documentation
//! Compatibility layer with the validator crate, which enables the `errors` prop to be automatically populated.

use axum::response::Response;
use serde_json::json;
use validator::{Validate, ValidationError, ValidationErrorsKind};

use super::PropChain;

impl<'route> PropChain<'route> {
    /// Validates the given `T`, applying the `"errors"` prop to the response if there are any validation errors
    /// and short-circuits
    pub async fn validate_and<T: Validate>(
        self,
        t: &T,
        and: impl AsyncFnOnce(Self) -> PropChain<'route>,
    ) -> Response {
        match t.validate() {
            Ok(_) => (and(self).await).await,
            Err(e) => {
                let mut errs = json!({});
                for (field, err) in e.into_errors() {
                    let ValidationErrorsKind::Field(ferrs) = err else {
                        panic!("only field validation errors currently supported")
                    };

                    let [
                        ValidationError {
                            message: Some(message),
                            ..
                        },
                    ] = ferrs.as_slice()
                    else {
                        panic!("only one field validation error with a message currently supported")
                    };

                    errs[field.to_string()] = json!(message);
                }

                self.inertia.extension.add_prop("errors", errs);
                self.await
            }
        }
    }
}