domainstack-axum 1.0.0

Axum extractors for domainstack: DomainJson<T> with automatic validation and structured error responses
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! # domainstack-axum
//!
//! Axum integration for domainstack validation with automatic DTO→Domain conversion.
//!
//! This crate provides Axum extractors that automatically deserialize, validate, and convert
//! DTOs to domain types—returning structured error responses on validation failure.
//!
//! ## What it provides
//!
//! - **`DomainJson<T, Dto>`** - Extract JSON, validate, and convert DTO to domain type in one step
//! - **`ValidatedJson<Dto>`** - Extract and validate a DTO without domain conversion
//! - **`ErrorResponse`** - Automatic structured error responses with field-level details
//!
//! ## Example - DomainJson
//!
//! ```rust,no_run
//! use axum::{routing::post, Router, Json};
//! use domainstack::prelude::*;
//! use domainstack_axum::{DomainJson, ErrorResponse};
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct CreateUserDto {
//!     name: String,
//!     age: u8,
//! }
//!
//! struct User {
//!     name: String,
//!     age: u8,
//! }
//!
//! impl TryFrom<CreateUserDto> for User {
//!     type Error = domainstack::ValidationError;
//!
//!     fn try_from(dto: CreateUserDto) -> Result<Self, Self::Error> {
//!         validate("name", dto.name.as_str(), &rules::min_len(2).and(rules::max_len(50)))?;
//!         validate("age", &dto.age, &rules::range(18, 120))?;
//!         Ok(Self { name: dto.name, age: dto.age })
//!     }
//! }
//!
//! // Type alias for cleaner handler signatures
//! type UserJson = DomainJson<User, CreateUserDto>;
//!
//! async fn create_user(
//!     UserJson { domain: user, .. }: UserJson
//! ) -> Result<Json<String>, ErrorResponse> {
//!     // user is guaranteed valid here!
//!     Ok(Json(format!("Created: {}", user.name)))
//! }
//!
//! // In your main.rs or server setup:
//! fn setup_router() -> Router {
//!     Router::new().route("/users", post(create_user))
//! }
//! ```
//!
//! ## Example - ValidatedJson
//!
//! ```rust,ignore
//! use axum::{routing::post, Router, Json};
//! use domainstack::Validate;
//! use domainstack_axum::{ValidatedJson, ErrorResponse};
//!
//! #[derive(Debug, Validate, serde::Deserialize)]
//! struct UserDto {
//!     #[validate(length(min = 2, max = 50))]
//!     name: String,
//!
//!     #[validate(range(min = 18, max = 120))]
//!     age: u8,
//! }
//!
//! async fn create_user(
//!     ValidatedJson(dto): ValidatedJson<UserDto>
//! ) -> Result<Json<UserDto>, ErrorResponse> {
//!     // dto is guaranteed valid here!
//!     Ok(Json(dto))
//! }
//! ```
//!
//! ## Error Response Format
//!
//! On validation failure, returns a 400 Bad Request with structured errors:
//!
//! ```json
//! {
//!   "code": "VALIDATION",
//!   "status": 400,
//!   "message": "Validation failed with 2 errors",
//!   "details": {
//!     "fields": {
//!       "name": [{"code": "min_length", "message": "Must be at least 2 characters"}],
//!       "age": [{"code": "out_of_range", "message": "Must be between 18 and 120"}]
//!     }
//!   }
//! }
//! ```

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    Json,
};
use domainstack::ValidationError;
use std::marker::PhantomData;

pub struct DomainJson<T, Dto = ()> {
    pub domain: T,
    _dto: PhantomData<Dto>,
}

impl<T, Dto> DomainJson<T, Dto> {
    pub fn new(domain: T) -> Self {
        Self {
            domain,
            _dto: PhantomData,
        }
    }
}

pub struct ErrorResponse(pub error_envelope::Error);

impl From<error_envelope::Error> for ErrorResponse {
    fn from(err: error_envelope::Error) -> Self {
        ErrorResponse(err)
    }
}

impl From<ValidationError> for ErrorResponse {
    fn from(err: ValidationError) -> Self {
        use domainstack_envelope::IntoEnvelopeError;
        ErrorResponse(err.into_envelope_error())
    }
}

#[axum::async_trait]
impl<T, Dto, S> FromRequest<S> for DomainJson<T, Dto>
where
    Dto: serde::de::DeserializeOwned,
    T: TryFrom<Dto, Error = ValidationError>,
    S: Send + Sync,
{
    type Rejection = ErrorResponse;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let Json(dto) = Json::<Dto>::from_request(req, state).await.map_err(|e| {
            ErrorResponse(error_envelope::Error::bad_request(format!(
                "Invalid JSON: {}",
                e
            )))
        })?;

        let domain = domainstack_http::into_domain(dto).map_err(ErrorResponse)?;

        Ok(DomainJson::new(domain))
    }
}

impl IntoResponse for ErrorResponse {
    fn into_response(self) -> Response {
        let status = axum::http::StatusCode::from_u16(self.0.status)
            .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);

        let body = serde_json::to_string(&self.0).unwrap_or_else(|_| {
            r#"{"code":"INTERNAL","message":"Serialization failed"}"#.to_string()
        });

        (status, body).into_response()
    }
}

pub struct ValidatedJson<Dto>(pub Dto);

#[axum::async_trait]
impl<Dto, S> FromRequest<S> for ValidatedJson<Dto>
where
    Dto: serde::de::DeserializeOwned + domainstack::Validate,
    S: Send + Sync,
{
    type Rejection = ErrorResponse;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let Json(dto) = Json::<Dto>::from_request(req, state).await.map_err(|e| {
            ErrorResponse(error_envelope::Error::bad_request(format!(
                "Invalid JSON: {}",
                e
            )))
        })?;

        dto.validate().map(|_| ValidatedJson(dto)).map_err(|e| {
            use domainstack_envelope::IntoEnvelopeError;
            ErrorResponse(e.into_envelope_error())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{routing::post, Router};
    use domainstack::{prelude::*, Validate};

    // DTOs used with DomainJson are just serde shapes
    // Validation happens during TryFrom conversion to domain
    #[derive(Debug, Clone, serde::Deserialize)]
    struct UserDto {
        name: String,
        age: u8,
    }

    #[derive(Debug, serde::Serialize)]
    struct User {
        name: String,
        age: u8,
    }

    impl TryFrom<UserDto> for User {
        type Error = ValidationError;

        fn try_from(dto: UserDto) -> Result<Self, Self::Error> {
            let mut err = ValidationError::new();

            let name_rule = rules::min_len(2).and(rules::max_len(50));
            if let Err(e) = validate("name", dto.name.as_str(), &name_rule) {
                err.extend(e);
            }

            let age_rule = rules::range(18, 120);
            if let Err(e) = validate("age", &dto.age, &age_rule) {
                err.extend(e);
            }

            if !err.is_empty() {
                return Err(err);
            }

            Ok(Self {
                name: dto.name,
                age: dto.age,
            })
        }
    }

    async fn create_user(DomainJson { domain: user, .. }: DomainJson<User, UserDto>) -> Json<User> {
        Json(user)
    }

    type UserJson = DomainJson<User, UserDto>;

    async fn create_user_with_alias(UserJson { domain: user, .. }: UserJson) -> Json<User> {
        Json(user)
    }

    async fn create_user_result_style(
        UserJson { domain: user, .. }: UserJson,
    ) -> Result<Json<User>, ErrorResponse> {
        Ok(Json(user))
    }

    #[tokio::test]
    async fn test_domain_json_valid() {
        let app = Router::new().route("/", post(create_user));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "Alice", "age": 30}))
            .await;

        response.assert_status_ok();
    }

    #[tokio::test]
    async fn test_domain_json_invalid() {
        let app = Router::new().route("/", post(create_user));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "A", "age": 200}))
            .await;

        response.assert_status_bad_request();

        let body: serde_json::Value = response.json();

        assert!(body["details"].is_object());
        assert_eq!(
            body["message"].as_str().unwrap(),
            "Validation failed with 2 errors"
        );

        let details = body["details"].as_object().unwrap();
        let fields = details["fields"].as_object().unwrap();

        assert!(fields.contains_key("name"));
        assert!(fields.contains_key("age"));
    }

    #[tokio::test]
    async fn test_domain_json_malformed_json() {
        let app = Router::new().route("/", post(create_user));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server.post("/").text("{invalid json").await;

        response.assert_status_bad_request();
    }

    #[tokio::test]
    async fn test_domain_json_missing_fields() {
        let app = Router::new().route("/", post(create_user));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "Alice"}))
            .await;

        response.assert_status_bad_request();
    }

    #[tokio::test]
    async fn test_type_alias_pattern() {
        let app = Router::new().route("/", post(create_user_with_alias));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "Alice", "age": 30}))
            .await;

        response.assert_status_ok();
    }

    #[tokio::test]
    async fn test_result_style_handler() {
        let app = Router::new().route("/", post(create_user_result_style));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "Alice", "age": 30}))
            .await;

        response.assert_status_ok();
    }

    // ValidatedJson tests - DTOs that derive Validate
    #[derive(Debug, Clone, Validate, serde::Deserialize, serde::Serialize)]
    struct ValidatedUserDto {
        #[validate(length(min = 2, max = 50))]
        name: String,

        #[validate(range(min = 18, max = 120))]
        age: u8,
    }

    async fn accept_validated_dto(
        ValidatedJson(dto): ValidatedJson<ValidatedUserDto>,
    ) -> Json<ValidatedUserDto> {
        Json(dto)
    }

    #[tokio::test]
    async fn test_validated_json_valid() {
        let app = Router::new().route("/", post(accept_validated_dto));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "Alice", "age": 30}))
            .await;

        response.assert_status_ok();
        let body: ValidatedUserDto = response.json();
        assert_eq!(body.name, "Alice");
        assert_eq!(body.age, 30);
    }

    #[tokio::test]
    async fn test_validated_json_invalid() {
        let app = Router::new().route("/", post(accept_validated_dto));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server
            .post("/")
            .json(&serde_json::json!({"name": "A", "age": 200}))
            .await;

        response.assert_status_bad_request();

        let body: serde_json::Value = response.json();
        assert_eq!(
            body["message"].as_str().unwrap(),
            "Validation failed with 2 errors"
        );

        let details = body["details"].as_object().unwrap();
        let fields = details["fields"].as_object().unwrap();

        assert!(fields.contains_key("name"));
        assert!(fields.contains_key("age"));
    }

    #[tokio::test]
    async fn test_validated_json_malformed_json() {
        let app = Router::new().route("/", post(accept_validated_dto));

        let server = axum_test::TestServer::new(app).unwrap();

        let response = server.post("/").text("{invalid json").await;

        response.assert_status_bad_request();
    }

    #[tokio::test]
    async fn test_error_response_into_response() {
        let err = ErrorResponse(error_envelope::Error::bad_request("Test error"));
        let response = err.into_response();
        assert_eq!(response.status(), axum::http::StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_error_response_custom_status() {
        let mut err = error_envelope::Error::bad_request("Test");
        err.status = 422;
        let response = ErrorResponse(err).into_response();
        assert_eq!(
            response.status(),
            axum::http::StatusCode::UNPROCESSABLE_ENTITY
        );
    }
}