#[cfg(test)]
pub mod test;
use crate::{HasValidate, ValidationRejection};
use axum::async_trait;
use axum::extract::{FromRequest, FromRequestParts, Request};
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};
use std::fmt::{Display, Formatter};
use std::ops::{Deref, DerefMut};
use validify::{Modify, Validate, ValidationErrors, ValidifyPayload};
#[derive(Debug, Clone, Copy, Default)]
pub struct Validated<E>(pub E);
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<T: Display> Display for Validated<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl<E> Validated<E> {
pub fn into_inner(self) -> E {
self.0
}
}
#[cfg(feature = "aide")]
impl<T> aide::OperationInput for Validated<T>
where
T: aide::OperationInput,
{
fn operation_input(ctx: &mut aide::gen::GenContext, operation: &mut aide::openapi::Operation) {
T::operation_input(ctx, operation);
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Modified<E>(pub E);
impl<E> Deref for Modified<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<E> DerefMut for Modified<E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T: Display> Display for Modified<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl<E> Modified<E> {
pub fn into_inner(self) -> E {
self.0
}
}
impl<E: IntoResponse + HasModify> IntoResponse for Modified<E> {
fn into_response(mut self) -> Response {
self.get_modify().modify();
self.0.into_response()
}
}
#[cfg(feature = "aide")]
impl<T> aide::OperationInput for Modified<T>
where
T: aide::OperationInput,
{
fn operation_input(ctx: &mut aide::gen::GenContext, operation: &mut aide::openapi::Operation) {
T::operation_input(ctx, operation);
}
}
#[cfg(feature = "aide")]
impl<T> aide::OperationOutput for Modified<T>
where
T: aide::OperationOutput,
{
type Inner = T::Inner;
fn operation_response(
ctx: &mut aide::gen::GenContext,
operation: &mut aide::openapi::Operation,
) -> Option<aide::openapi::Response> {
T::operation_response(ctx, operation)
}
fn inferred_responses(
ctx: &mut aide::gen::GenContext,
operation: &mut aide::openapi::Operation,
) -> Vec<(Option<u16>, aide::openapi::Response)> {
T::inferred_responses(ctx, operation)
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Validified<E>(pub E);
impl<E> Deref for Validified<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<E> DerefMut for Validified<E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T: Display> Display for Validified<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl<E> Validified<E> {
pub fn into_inner(self) -> E {
self.0
}
}
#[cfg(feature = "aide")]
impl<T> aide::OperationInput for Validified<T>
where
T: aide::OperationInput,
{
fn operation_input(ctx: &mut aide::gen::GenContext, operation: &mut aide::openapi::Operation) {
T::operation_input(ctx, operation);
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidifiedByRef<E>(pub E);
impl<E> Deref for ValidifiedByRef<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<E> DerefMut for ValidifiedByRef<E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T: Display> Display for ValidifiedByRef<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl<E> ValidifiedByRef<E> {
pub fn into_inner(self) -> E {
self.0
}
}
#[cfg(feature = "aide")]
impl<T> aide::OperationInput for ValidifiedByRef<T>
where
T: aide::OperationInput,
{
fn operation_input(ctx: &mut aide::gen::GenContext, operation: &mut aide::openapi::Operation) {
T::operation_input(ctx, operation);
}
}
pub type ValidifyRejection<E> = ValidationRejection<ValidationErrors, E>;
impl<E> From<ValidationErrors> for ValidifyRejection<E> {
fn from(value: ValidationErrors) -> Self {
Self::Valid(value)
}
}
pub trait HasModify {
type Modify: Modify;
fn get_modify(&mut self) -> &mut Self::Modify;
}
pub trait PayloadExtractor {
type Payload;
fn get_payload(self) -> Self::Payload;
}
pub trait HasValidify: Sized {
type Validify: ValidifyPayload;
type PayloadExtractor: PayloadExtractor<Payload = <Self::Validify as ValidifyPayload>::Payload>;
fn from_validify(v: Self::Validify) -> Self;
}
#[async_trait]
impl<State, Extractor> FromRequest<State> for Validated<Extractor>
where
State: Send + Sync,
Extractor: HasValidate + FromRequest<State>,
Extractor::Validate: validify::Validate,
{
type Rejection = ValidifyRejection<<Extractor as FromRequest<State>>::Rejection>;
async fn from_request(req: Request, state: &State) -> Result<Self, Self::Rejection> {
let inner = Extractor::from_request(req, state)
.await
.map_err(ValidifyRejection::Inner)?;
inner.get_validate().validate()?;
Ok(Validated(inner))
}
}
#[async_trait]
impl<State, Extractor> FromRequestParts<State> for Validated<Extractor>
where
State: Send + Sync,
Extractor: HasValidate + FromRequestParts<State>,
Extractor::Validate: Validate,
{
type Rejection = ValidifyRejection<<Extractor as FromRequestParts<State>>::Rejection>;
async fn from_request_parts(parts: &mut Parts, state: &State) -> Result<Self, Self::Rejection> {
let inner = Extractor::from_request_parts(parts, state)
.await
.map_err(ValidifyRejection::Inner)?;
inner.get_validate().validate()?;
Ok(Validated(inner))
}
}
#[async_trait]
impl<State, Extractor> FromRequest<State> for Modified<Extractor>
where
State: Send + Sync,
Extractor: HasModify + FromRequest<State>,
{
type Rejection = <Extractor as FromRequest<State>>::Rejection;
async fn from_request(req: Request, state: &State) -> Result<Self, Self::Rejection> {
let mut inner = Extractor::from_request(req, state).await?;
inner.get_modify().modify();
Ok(Modified(inner))
}
}
#[async_trait]
impl<State, Extractor> FromRequestParts<State> for Modified<Extractor>
where
State: Send + Sync,
Extractor: HasModify + FromRequestParts<State>,
{
type Rejection = <Extractor as FromRequestParts<State>>::Rejection;
async fn from_request_parts(parts: &mut Parts, state: &State) -> Result<Self, Self::Rejection> {
let mut inner = Extractor::from_request_parts(parts, state).await?;
inner.get_modify().modify();
Ok(Modified(inner))
}
}
#[async_trait]
impl<State, Extractor> FromRequest<State> for Validified<Extractor>
where
State: Send + Sync,
Extractor: HasValidify,
Extractor::PayloadExtractor: FromRequest<State>,
{
type Rejection =
ValidifyRejection<<Extractor::PayloadExtractor as FromRequest<State>>::Rejection>;
async fn from_request(req: Request, state: &State) -> Result<Self, Self::Rejection> {
let payload = Extractor::PayloadExtractor::from_request(req, state)
.await
.map_err(ValidifyRejection::Inner)?
.get_payload();
let validify = Extractor::Validify::validify_from(payload)?;
Ok(Validified(Extractor::from_validify(validify)))
}
}
#[async_trait]
impl<State, Extractor> FromRequestParts<State> for Validified<Extractor>
where
State: Send + Sync,
Extractor: HasValidify,
Extractor::PayloadExtractor: FromRequestParts<State>,
{
type Rejection =
ValidifyRejection<<Extractor::PayloadExtractor as FromRequestParts<State>>::Rejection>;
async fn from_request_parts(parts: &mut Parts, state: &State) -> Result<Self, Self::Rejection> {
let payload = Extractor::PayloadExtractor::from_request_parts(parts, state)
.await
.map_err(ValidifyRejection::Inner)?
.get_payload();
let validify = Extractor::Validify::validify_from(payload)?;
Ok(Validified(Extractor::from_validify(validify)))
}
}
#[async_trait]
impl<State, Extractor> FromRequest<State> for ValidifiedByRef<Extractor>
where
State: Send + Sync,
Extractor: HasValidate + HasModify + FromRequest<State>,
Extractor::Validate: Validate,
{
type Rejection = ValidifyRejection<<Extractor as FromRequest<State>>::Rejection>;
async fn from_request(req: Request, state: &State) -> Result<Self, Self::Rejection> {
let mut inner = Extractor::from_request(req, state)
.await
.map_err(ValidifyRejection::Inner)?;
inner.get_modify().modify();
inner.get_validate().validate()?;
Ok(ValidifiedByRef(inner))
}
}
#[async_trait]
impl<State, Extractor> FromRequestParts<State> for ValidifiedByRef<Extractor>
where
State: Send + Sync,
Extractor: HasValidate + HasModify + FromRequestParts<State>,
Extractor::Validate: Validate,
{
type Rejection = ValidifyRejection<<Extractor as FromRequestParts<State>>::Rejection>;
async fn from_request_parts(parts: &mut Parts, state: &State) -> Result<Self, Self::Rejection> {
let mut inner = Extractor::from_request_parts(parts, state)
.await
.map_err(ValidifyRejection::Inner)?;
inner.get_modify().modify();
inner.get_validate().validate()?;
Ok(ValidifiedByRef(inner))
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::Json;
use serde::Serialize;
use std::error::Error;
use std::io;
const VALIDIFY: &str = "validify";
#[test]
fn validify_deref_deref_mut_into_inner() {
let mut inner = String::from(VALIDIFY);
let mut v = Validated(inner.clone());
assert_eq!(&inner, v.deref());
inner.push_str(VALIDIFY);
v.deref_mut().push_str(VALIDIFY);
assert_eq!(&inner, v.deref());
println!("{}", v);
assert_eq!(inner, v.into_inner());
let mut inner = String::from(VALIDIFY);
let mut v = Modified(inner.clone());
assert_eq!(&inner, v.deref());
inner.push_str(VALIDIFY);
v.deref_mut().push_str(VALIDIFY);
assert_eq!(&inner, v.deref());
println!("{}", v);
assert_eq!(inner, v.into_inner());
let mut inner = String::from(VALIDIFY);
let mut v = Validified(inner.clone());
assert_eq!(&inner, v.deref());
inner.push_str(VALIDIFY);
v.deref_mut().push_str(VALIDIFY);
assert_eq!(&inner, v.deref());
println!("{}", v);
assert_eq!(inner, v.into_inner());
let mut inner = String::from(VALIDIFY);
let mut v = ValidifiedByRef(inner.clone());
assert_eq!(&inner, v.deref());
inner.push_str(VALIDIFY);
v.deref_mut().push_str(VALIDIFY);
assert_eq!(&inner, v.deref());
println!("{}", v);
assert_eq!(inner, v.into_inner());
}
#[test]
fn display_error() {
let mut report = ValidationErrors::new();
report.add(validify::ValidationError::new_schema(VALIDIFY));
let s = report.to_string();
let vr = ValidifyRejection::<String>::Valid(report);
assert_eq!(vr.to_string(), s);
let inner = String::from(VALIDIFY);
let vr = ValidifyRejection::<String>::Inner(inner.clone());
assert_eq!(inner.to_string(), vr.to_string());
let mut report = ValidationErrors::new();
report.add(validify::ValidationError::new_schema(VALIDIFY));
let vr = ValidifyRejection::<io::Error>::Valid(report);
assert!(
matches!(vr.source(), Some(source) if source.downcast_ref::<ValidationErrors>().is_some())
);
let vr =
ValidifyRejection::<io::Error>::Inner(io::Error::new(io::ErrorKind::Other, VALIDIFY));
assert!(
matches!(vr.source(), Some(source) if source.downcast_ref::<io::Error>().is_some())
);
}
#[test]
fn modified_into_response() {
use validify::Validify;
#[derive(Validify, Serialize)]
struct Data {
#[modify(trim)]
v: String,
}
println!(
"{:?}",
Modified(Json(Data { v: "a ".into() })).into_response()
);
}
}