use std::{
fmt::Display,
ops::{Deref, DerefMut},
};
use axum::{
Form, Json,
extract::{FromRequest, FromRequestParts, Path, Query, Request},
http::request::Parts,
};
#[cfg(feature = "multipart")]
use axum_typed_multipart::TypedMultipart;
use axum_valid::{HasValidify, ValidationRejection, Validified};
use validify::ValidationErrors;
#[cfg(feature = "multipart")]
use validify::Validify;
use crate::web::response::ApiError;
pub const DEFAULT_VALIDATION_ERROR_CODE: u32 = 400_001;
fn map_inner_rejection(error: impl Display) -> ApiError {
ApiError::err_invalid_param(error.to_string())
}
fn map_validation_errors(errors: &ValidationErrors) -> ApiError {
errors.errors().first().map_or_else(
|| ApiError::err_invalid_param("请求参数校验失败"),
|error| {
let message = error.message().unwrap_or_else(|| "请求参数校验失败".into());
ApiError::err_invalid_param(message)
},
)
}
fn map_validation_rejection<E>(error: ValidationRejection<ValidationErrors, E>) -> ApiError
where
E: Display,
{
match error {
ValidationRejection::Valid(errors) => map_validation_errors(&errors),
ValidationRejection::Inner(error) => map_inner_rejection(error),
}
}
#[derive(Clone, Copy, Debug)]
pub struct Validated<E>(pub E);
impl<E> Validated<E> {
pub fn into_inner(self) -> E {
self.0
}
}
impl<E> AsRef<E> for Validated<E> {
fn as_ref(&self) -> &E {
&self.0
}
}
impl<E> Deref for Validated<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<E> DerefMut for Validated<E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<S, E> FromRequest<S> for Validated<E>
where
S: Send + Sync,
E: HasValidify,
E::PayloadExtractor: FromRequest<S>,
<E::PayloadExtractor as FromRequest<S>>::Rejection: Display,
{
type Rejection = ApiError;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
let Validified(value) = Validified::<E>::from_request(request, state)
.await
.map_err(map_validation_rejection)?;
Ok(Self(value))
}
}
impl<S, E> FromRequestParts<S> for Validated<E>
where
S: Send + Sync,
E: HasValidify,
E::PayloadExtractor: FromRequestParts<S>,
<E::PayloadExtractor as FromRequestParts<S>>::Rejection: Display,
{
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let Validified(value) = Validified::<E>::from_request_parts(parts, state)
.await
.map_err(map_validation_rejection)?;
Ok(Self(value))
}
}
pub type ValidatedJson<T> = Validated<Json<T>>;
pub type ValidatedQuery<T> = Validated<Query<T>>;
pub type ValidatedPath<T> = Validated<Path<T>>;
pub type ValidatedFormUrl<T> = Validated<Form<T>>;
#[cfg(feature = "multipart")]
#[derive(Clone, Debug)]
pub struct ValidatedFormData<T>(pub T);
#[cfg(feature = "multipart")]
impl<T> ValidatedFormData<T> {
pub fn into_inner(self) -> T {
self.0
}
}
#[cfg(feature = "multipart")]
impl<T> AsRef<T> for ValidatedFormData<T> {
fn as_ref(&self) -> &T {
&self.0
}
}
#[cfg(feature = "multipart")]
impl<T> Deref for ValidatedFormData<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "multipart")]
impl<T> DerefMut for ValidatedFormData<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "multipart")]
impl<S, T> FromRequest<S> for ValidatedFormData<T>
where
S: Send + Sync,
T: Validify,
TypedMultipart<T>: FromRequest<S>,
<TypedMultipart<T> as FromRequest<S>>::Rejection: Display,
{
type Rejection = ApiError;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
let TypedMultipart(mut value) = TypedMultipart::<T>::from_request(request, state)
.await
.map_err(map_inner_rejection)?;
value
.validify()
.map_err(|errors| map_validation_errors(&errors))?;
Ok(Self(value))
}
}
#[cfg(test)]
mod tests {
use validify::ValidationError;
use super::*;
#[test]
fn validation_uses_invalid_param_code_and_preserves_message() {
let mut errors = ValidationErrors::new();
errors.add(
ValidationError::new_field_named("name", "42001").with_message("名称不能为空".into()),
);
let error = map_validation_errors(&errors);
assert_eq!(error.code, DEFAULT_VALIDATION_ERROR_CODE);
assert_eq!(error.msg, "名称不能为空");
}
#[test]
fn validation_without_custom_message_uses_safe_default() {
let mut errors = ValidationErrors::new();
errors.add(ValidationError::new_field_named("name", "length"));
let error = map_validation_errors(&errors);
assert_eq!(error.code, DEFAULT_VALIDATION_ERROR_CODE);
assert_eq!(error.msg, "请求参数校验失败");
}
#[test]
fn empty_validation_errors_use_safe_default() {
let error = map_validation_errors(&ValidationErrors::new());
assert_eq!(error.code, DEFAULT_VALIDATION_ERROR_CODE);
assert_eq!(error.msg, "请求参数校验失败");
}
}