diff --git a/Cargo.toml b/Cargo.toml index b40e08f..830aefa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "axum-valid" -version = "0.1.0" +version = "0.2.0" description = "Validator for axum" authors = ["GengTeng "] license = "MIT" @@ -19,9 +19,6 @@ categories = [ ] edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [dependencies] axum = "0.6.18" validator = "0.16.0" diff --git a/README.md b/README.md index 640d081..ad06e94 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,33 @@ # axum-valid +The Valid crate provides a `Valid` type that can be used in combination with `Json`, `Path`, `Query`, and `Form` types to validate the entities that implement the `Validate` trait. + +## Usage + +```rust +use validator::Validate; +use serde::Deserialize; + +#[derive(Debug, Validate, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Pager { + #[validate(range(min = 1, max = 50))] + page_size: usize, + #[validate(range(min = 1))] + page_no: usize, +} + +pub async fn get_page_by_query( + Valid(Query(pager)): Valid>, +) { + assert!((1..=50).contains(pager.page_size)); + assert!((1..).contains(pager.page_no)); +} + +pub async fn get_page_by_json( + Valid(Json(pager)): Valid>, +) { + assert!((1..=50).contains(pager.page_size)); + assert!((1..).contains(pager.page_no)); +} +``` \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 4b8a111..ae6b69e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,9 +6,12 @@ use axum::response::{IntoResponse, Response}; use axum::{async_trait, Form, Json}; use validator::{Validate, ValidationErrors}; +/// Valid entity extractor #[derive(Debug, Clone, Copy, Default)] pub struct Valid(pub T); +/// If the valid extractor fails it'll use this "rejection" type. +/// This rejection type can be converted into a response. pub enum ValidRejection { Valid(ValidationErrors), Inner(E), @@ -55,9 +58,14 @@ impl From for ValidRejection { } } +/// Trait for types that can provide a reference that can be validated for correctness. pub trait HasValidate { + /// Inner type that can be validated for correctness type Validate: Validate; - type Rejection; + /// If the inner extractor fails it'll use this "rejection" type. + /// A rejection is a kind of error that can be converted into a response. + type Rejection: IntoResponse; + /// get the inner type fn get_validate(&self) -> &Self::Validate; } @@ -100,7 +108,6 @@ where B: Send + Sync + 'static, T: HasValidate + FromRequest, T::Validate: Validate, - ::Rejection: IntoResponse, ValidRejection<::Rejection>: From<>::Rejection>, { type Rejection = ValidRejection<::Rejection>; @@ -118,7 +125,6 @@ where S: Send + Sync + 'static, T: HasValidate + FromRequestParts, T::Validate: Validate, - ::Rejection: IntoResponse, ValidRejection<::Rejection>: From<>::Rejection>, { type Rejection = ValidRejection<::Rejection>;