Module axum_valid::sonic

source ·
Expand description

§Support for Sonic<T>

§Feature

Enable the sonic feature to use Valid<Sonic<T>>.

§Usage

  1. Implement Deserialize and Validate for your data type T.
  2. In your handler function, use Valid<Sonic<T>> as some parameter’s type.

§Example

#[cfg(feature = "validator")]
mod validator_example {
    use axum::routing::post;
    use axum_serde::Sonic;
    use axum::Router;
    use axum_valid::Valid;
    use serde::Deserialize;
    use validator::Validate;
     
    pub fn router() -> Router {
        Router::new().route("/sonic", post(handler))
    }

    async fn handler(Valid(Sonic(parameter)): Valid<Sonic<Parameter>>) {
        assert!(parameter.validate().is_ok());
        // Support automatic dereferencing
        println!("v0 = {}, v1 = {}", parameter.v0, parameter.v1);
    }

    #[derive(Validate, Deserialize)]
    pub struct Parameter {
        #[validate(range(min = 5, max = 10))]
        pub v0: i32,
        #[validate(length(min = 1, max = 10))]
        pub v1: String,
    }
}

#[cfg(feature = "garde")]
mod garde_example {
    use axum::routing::post;
    use axum_serde::Sonic;
    use axum::Router;
    use axum_valid::Garde;
    use serde::Deserialize;
    use garde::Validate;

    pub fn router() -> Router {
        Router::new().route("/sonic", post(handler))
    }

    async fn handler(Garde(Sonic(parameter)): Garde<Sonic<Parameter>>) {
        assert!(parameter.validate(&()).is_ok());
        // Support automatic dereferencing
        println!("v0 = {}, v1 = {}", parameter.v0, parameter.v1);
    }

    #[derive(Validate, Deserialize)]
    pub struct Parameter {
        #[garde(range(min = 5, max = 10))]
        pub v0: i32,
        #[garde(length(min = 1, max = 10))]
        pub v1: String,
    }
}