use axum::response::Response;
use serde_json::json;
use validator::{Validate, ValidationError, ValidationErrorsKind};
use super::PropChain;
impl<'route> PropChain<'route> {
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
}
}
}
}