Skip to main content

scrutiny_axum/
lib.rs

1//! Axum integration for the `scrutiny` crate.
2//!
3//! Provides extractors that deserialize **and** validate request data in one step.
4//! Deserialization errors are reported as field-level validation errors — not generic
5//! error strings. This means typed fields like `uuid::Uuid` or `chrono::NaiveDate`
6//! produce the same structured error format as validation failures.
7//!
8//! # Extractors
9//!
10//! | Extractor | Wraps | Description |
11//! |-----------|-------|-------------|
12//! | [`Valid<T>`] | `Json<T>` | JSON body with validation |
13//! | [`ValidWith<T, E>`] | `Json<T>` | JSON body with custom error response |
14//! | [`ValidForm<T>`] | `Form<T>` | Form-encoded body with validation |
15//! | [`ValidQuery<T>`] | axum-extra's `Query<T>` | Query parameters with validation (uses `serde_html_form`) |
16//!
17//! # Quick Start
18//!
19//! ```rust,ignore
20//! use scrutiny::Validate;
21//! use scrutiny_axum::Valid;
22//! use axum::{Router, routing::post, response::IntoResponse, Json};
23//! use serde::Deserialize;
24//!
25//! #[derive(Validate, Deserialize)]
26//! struct CreateUser {
27//!     #[validate(required, min = 2)]
28//!     name: Option<String>,
29//!     id: uuid::Uuid,  // deserialization error → field-level validation error
30//! }
31//!
32//! async fn create_user(Valid(user): Valid<CreateUser>) -> impl IntoResponse {
33//!     Json(serde_json::json!({ "name": user.name }))
34//! }
35//!
36//! let app = Router::new().route("/users", post(create_user));
37//! ```
38//!
39//! Both validation failures and deserialization errors produce the same format:
40//!
41//! ```json
42//! {
43//!   "message": "The given data was invalid.",
44//!   "errors": {
45//!     "name": ["The name field is required."],
46//!     "id": ["invalid type: string \"not-a-uuid\", expected UUID"]
47//!   }
48//! }
49//! ```
50//!
51//! # Replaces `WithRejection` from axum-extra
52//!
53//! These extractors are standalone replacements for the common
54//! `WithRejection<Json<T>, AppError>` pattern from `axum-extra`. You don't need
55//! `axum-extra` or `WithRejection` — our extractors handle deserialization,
56//! validation, and error responses in one step.
57//!
58//! ```rust,ignore
59//! // Before (axum-extra):
60//! use axum_extra::extract::WithRejection;
61//! async fn handler(
62//!     WithRejection(Json(body), _): WithRejection<Json<CreateUser>, AppError>,
63//! ) -> Result<impl IntoResponse> { ... }
64//!
65//! // After (scrutiny-axum):
66//! use scrutiny_axum::Valid;
67//! async fn handler(Valid(body): Valid<CreateUser>) -> impl IntoResponse { ... }
68//!
69//! // With custom error format (replaces AppError):
70//! use scrutiny_axum::ValidWith;
71//! async fn handler(r: ValidWith<CreateUser, MyApiError>) -> impl IntoResponse { ... }
72//! ```
73//!
74//! # Custom Error Responses
75//!
76//! Implement [`ValidationErrorResponse`] to control the HTTP response format:
77//!
78//! ```rust,ignore
79//! use scrutiny_axum::{ValidWith, ValidationErrorResponse};
80//!
81//! struct MyApiError;
82//! impl ValidationErrorResponse for MyApiError {
83//!     fn from_validation_errors(errors: ValidationErrors) -> Response { /* ... */ }
84//! }
85//!
86//! async fn handler(result: ValidWith<CreateUser, MyApiError>) -> impl IntoResponse {
87//!     let user = result.into_inner();
88//!     // ...
89//! }
90//! ```
91
92use axum::extract::{FromRequest, Request};
93use axum::response::{IntoResponse, Response};
94use http::StatusCode;
95use scrutiny::deserialize::deserialize_json;
96use scrutiny::error::{ValidationError, ValidationErrors};
97use scrutiny::traits::Validate;
98use std::marker::PhantomData;
99
100/// Trait for customizing how validation errors become HTTP responses.
101/// Implement this to use your own error format with `ValidWith<T, E>`.
102///
103/// Both deserialization errors and validation errors are unified into
104/// `ValidationErrors` before being passed to this trait.
105pub trait ValidationErrorResponse: Send + Sync + 'static {
106    fn from_validation_errors(errors: ValidationErrors) -> Response;
107}
108
109/// Default error response: Laravel-compatible 422 JSON.
110pub struct DefaultErrorResponse;
111
112impl ValidationErrorResponse for DefaultErrorResponse {
113    fn from_validation_errors(errors: ValidationErrors) -> Response {
114        let body = serde_json::json!({
115            "message": "The given data was invalid.",
116            "errors": errors
117        });
118        (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response()
119    }
120}
121
122/// Deserialize a query/form string using `serde_html_form` (same parser as
123/// axum-extra's `Query`) wrapped with `serde_path_to_error` for field-level errors.
124///
125/// Supports repeated params (`?tag=a&tag=b` → `Vec`), bracket notation
126/// (`?user[name]=Jo`), and other formats that basic `serde_urlencoded` doesn't.
127fn deserialize_query<T: serde::de::DeserializeOwned>(query: &str) -> Result<T, ValidationErrors> {
128    serde_html_form::from_str::<T>(query).map_err(|err| {
129        let mut errors = ValidationErrors::new();
130        errors.add(
131            "_query",
132            ValidationError::new("deserialization", err.to_string()),
133        );
134        errors
135    })
136}
137
138// ── Valid<T> — the simple extractor with default error response ──
139
140/// Extracts and validates JSON body. Drop-in replacement for `axum::Json<T>`.
141///
142/// Deserialization errors are converted to field-level validation errors using
143/// `serde_path_to_error`, so typed fields like `uuid::Uuid` produce structured
144/// errors on the correct field name.
145///
146/// ```ignore
147/// async fn create_user(Valid(user): Valid<CreateUser>) -> impl IntoResponse {
148///     // user is already deserialized and validated
149/// }
150/// ```
151pub struct Valid<T>(pub T);
152
153impl<T, S> FromRequest<S> for Valid<T>
154where
155    T: serde::de::DeserializeOwned + Validate + Send,
156    S: Send + Sync,
157{
158    type Rejection = Response;
159
160    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
161        let body = axum::body::to_bytes(req.into_body(), usize::MAX)
162            .await
163            .map_err(|e| {
164                let mut errors = ValidationErrors::new();
165                errors.add("_body", ValidationError::new("body", e.to_string()));
166                DefaultErrorResponse::from_validation_errors(errors)
167            })?;
168
169        let value: T =
170            deserialize_json(&body).map_err(DefaultErrorResponse::from_validation_errors)?;
171
172        value
173            .validate()
174            .map_err(DefaultErrorResponse::from_validation_errors)?;
175
176        Ok(Valid(value))
177    }
178}
179
180// ── ValidWith<T, E> — customizable error response ──
181
182/// Extracts and validates JSON body with a custom error response type.
183///
184/// ```ignore
185/// async fn handler(result: ValidWith<CreateUser, MyApiError>) -> impl IntoResponse {
186///     let user = result.into_inner();
187/// }
188/// ```
189pub struct ValidWith<T, E: ValidationErrorResponse = DefaultErrorResponse>(pub T, PhantomData<E>);
190
191impl<T, E: ValidationErrorResponse> ValidWith<T, E> {
192    pub fn into_inner(self) -> T {
193        self.0
194    }
195}
196
197impl<T, E, S> FromRequest<S> for ValidWith<T, E>
198where
199    T: serde::de::DeserializeOwned + Validate + Send,
200    E: ValidationErrorResponse,
201    S: Send + Sync,
202{
203    type Rejection = Response;
204
205    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
206        let body = axum::body::to_bytes(req.into_body(), usize::MAX)
207            .await
208            .map_err(|e| {
209                let mut errors = ValidationErrors::new();
210                errors.add("_body", ValidationError::new("body", e.to_string()));
211                E::from_validation_errors(errors)
212            })?;
213
214        let value: T = deserialize_json(&body).map_err(E::from_validation_errors)?;
215
216        value.validate().map_err(E::from_validation_errors)?;
217
218        Ok(ValidWith(value, PhantomData))
219    }
220}
221
222// ── ValidForm<T> — form data extraction + validation ──
223
224/// Extracts and validates form-encoded body.
225///
226/// Uses `serde_html_form` for deserialization (same parser as axum-extra).
227pub struct ValidForm<T>(pub T);
228
229impl<T, S> FromRequest<S> for ValidForm<T>
230where
231    T: serde::de::DeserializeOwned + Validate + Send,
232    S: Send + Sync,
233{
234    type Rejection = Response;
235
236    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
237        let body = axum::body::to_bytes(req.into_body(), usize::MAX)
238            .await
239            .map_err(|e| {
240                let mut errors = ValidationErrors::new();
241                errors.add("_body", ValidationError::new("body", e.to_string()));
242                DefaultErrorResponse::from_validation_errors(errors)
243            })?;
244
245        let query_str = std::str::from_utf8(&body).map_err(|e| {
246            let mut errors = ValidationErrors::new();
247            errors.add("_body", ValidationError::new("encoding", e.to_string()));
248            DefaultErrorResponse::from_validation_errors(errors)
249        })?;
250
251        let value: T =
252            deserialize_query(query_str).map_err(DefaultErrorResponse::from_validation_errors)?;
253
254        value
255            .validate()
256            .map_err(DefaultErrorResponse::from_validation_errors)?;
257
258        Ok(ValidForm(value))
259    }
260}
261
262// ── ValidQuery<T> — query parameter extraction + validation ──
263
264/// Extracts and validates query parameters.
265///
266/// Uses `serde_html_form` for deserialization (same parser as axum-extra's `Query`),
267/// which supports repeated params (`?tag=a&tag=b` → `Vec<String>`) and bracket
268/// notation (`?user[name]=Jo`).
269///
270/// **Note for users coming from plain axum**: this uses a more capable query string
271/// parser than axum's built-in `Query` extractor (which uses `serde_urlencoded`).
272/// The behavior is the same as axum-extra's `Query`. This means some edge cases in
273/// query string parsing may behave differently from what you're used to with
274/// `axum::extract::Query`.
275pub struct ValidQuery<T>(pub T);
276
277impl<T, S> FromRequest<S> for ValidQuery<T>
278where
279    T: serde::de::DeserializeOwned + Validate + Send,
280    S: Send + Sync,
281{
282    type Rejection = Response;
283
284    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
285        let query_str = req.uri().query().unwrap_or("");
286
287        let value: T =
288            deserialize_query(query_str).map_err(DefaultErrorResponse::from_validation_errors)?;
289
290        value
291            .validate()
292            .map_err(DefaultErrorResponse::from_validation_errors)?;
293
294        Ok(ValidQuery(value))
295    }
296}