add support for validify

This commit is contained in:
gengteng
2023-10-19 23:12:32 +08:00
parent 61bf3c5b23
commit b2d2c3d7ca
14 changed files with 1139 additions and 354 deletions

View File

@@ -2,7 +2,7 @@
//!
//! ## Feature
//!
//! Enable the `validify` feature to use `Validated<E>`, `Modified<E>` and `Validified<E>`.
//! Enable the `validify` feature to use `Validated<E>`, `Modified<E>`, `Validified<E>` and `ValidifiedByRef<E>`.
//!
#[cfg(test)]
@@ -20,6 +20,10 @@ use validify::{Modify, Validate, ValidationErrors, Validify};
/// # `Validated` data extractor
///
/// `Validated` provides simple data validation based on `validify`.
///
/// It only does validation, usage is similar to `Valid`.
///
#[derive(Debug, Clone, Copy, Default)]
pub struct Validated<E>(pub E);
@@ -44,7 +48,7 @@ impl<T: Display> Display for Validated<T> {
}
impl<E> Validated<E> {
/// Consumes the `Validified` and returns the validated data within.
/// Consumes the `Validated` and returns the validated data within.
///
/// This returns the `E` type which represents the data that has been
/// successfully validated.
@@ -55,6 +59,20 @@ impl<E> Validated<E> {
/// # `Modified` data extractor / response
///
/// ## Extractor
///
/// `Modified` uses `validify`'s modification capabilities to alter data, without validation.
///
/// Operations like trimming and case modification can be done based on `modify` attributes.
///
/// ## Response
///
/// `Modified` also implements the `IntoResponse` trait. When its inner `IntoResponse` type also implements the `HasModify` trait:
///
/// `Modified` will call `validify`'s modify method to alter the inner data.
/// Then call the inner type's own `into_response` method to convert it into a HTTP response.
///
/// This allows applying modifications during response conversion by leveraging validify.
#[derive(Debug, Clone, Copy, Default)]
pub struct Modified<E>(pub E);
@@ -97,6 +115,12 @@ impl<E: IntoResponse + HasModify> IntoResponse for Modified<E> {
/// # `Validified` data extractor
///
/// `Validified` provides construction, modification and validation abilities based on `validify`.
///
/// It requires a serde-based inner extractor.
///
/// And can treat missing fields as validation errors.
///
#[derive(Debug, Clone, Copy, Default)]
pub struct Validified<E>(pub E);
@@ -121,7 +145,7 @@ impl<T: Display> Display for Validified<T> {
}
impl<E> Validified<E> {
/// Consumes the `ValidifiedMut` and returns the modified and validated data within.
/// Consumes the `Validified` and returns the modified and validated data within.
///
/// This returns the `E` type which represents the data that has been
/// successfully validated.
@@ -130,7 +154,46 @@ impl<E> Validified<E> {
}
}
/// `ValidifyRejection` is returned when the `Validified` / `ValidifiedMut` / `Modified` extractor fails.
/// # `ValidifiedByRef` data extractor
///
/// `ValidifiedByRef` is similar to `Validified`, but operates via reference.
///
/// Suitable for inner extractors not based on `serde`.
///
#[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> {
/// Consumes the `ValidifiedByRef` and returns the modified and validated data within.
///
/// This returns the `E` type which represents the data that has been
/// successfully validated.
pub fn into_inner(self) -> E {
self.0
}
}
/// `ValidifyRejection` is returned when the `Validated` / `Modified` / `Validified` / `ValidifiedByRef` extractor fails.
///
pub type ValidifyRejection<E> = ValidationRejection<ValidationErrors, E>;
@@ -159,16 +222,21 @@ pub trait PayloadExtractor {
fn get_payload(self) -> Self::Payload;
}
/// Trait for types that can supply a reference that can be modified and validated using `validify`.
/// Trait for extractors whose inner data type that can be constructed using some payload,
/// then modified and validated using `validify`.
///
/// Extractor types `T` that implement this trait can be used with `Validified`.
///
pub trait HasValidify: Sized {
/// Inner type that can be modified and validated using `validify`.
type Validify: Validify;
///
/// Extracts payload from the request,
/// which will be used to construct the `Self::Validify` type
/// and perform modification and validation on it.
type PayloadExtractor: PayloadExtractor<Payload = <Self::Validify as Validify>::Payload>;
///
/// Re-packages the validified data back into the inner Extractor type.
fn from_validified(v: Self::Validify) -> Self;
}
@@ -282,3 +350,42 @@ where
)))
}
}
#[async_trait]
impl<State, Body, Extractor> FromRequest<State, Body> for ValidifiedByRef<Extractor>
where
State: Send + Sync,
Body: Send + Sync + 'static,
Extractor: HasValidate + HasModify + FromRequest<State, Body>,
Extractor::Validate: Validate,
{
type Rejection = ValidifyRejection<<Extractor as FromRequest<State, Body>>::Rejection>;
async fn from_request(req: Request<Body>, 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))
}
}