domainstack 1.1.1

Write validation once, use everywhere: Rust rules auto-generate JSON Schema + OpenAPI + TypeScript/Zod. WASM browser validation. Axum/Actix/Rocket adapters.
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# HTTP Integration

**Complete guide to integrating domainstack validation with web frameworks: Axum, Actix-web, and Rocket.**

## Table of Contents

- [Overview]#overview
- [Error Response Format]#error-response-format
- [Axum Integration]#axum-integration
- [Actix-web Integration]#actix-web-integration
- [Rocket Integration]#rocket-integration
- [Framework Comparison]#framework-comparison
- [Domain Modeling for HTTP]#domain-modeling-for-http
- [Error Customization]#error-customization
- [Client-Side Error Handling]#client-side-error-handling
- [Testing HTTP Endpoints]#testing-http-endpoints

## Overview

domainstack provides framework adapters that convert validation errors to structured HTTP responses automatically:

| Framework | Crate | Extractor |
|-----------|-------|-----------|
| **Axum** | `domainstack-axum` | `DomainJson<T, Dto>`, `ValidatedJson<Dto>` |
| **Actix-web** | `domainstack-actix` | `DomainJson<T, Dto>`, `ValidatedJson<Dto>` |
| **Rocket** | `domainstack-rocket` | `DomainJson<T, Dto>`, `ValidatedJson<Dto>` |

**All adapters provide:**
- Automatic JSON deserialization
- DTO → Domain conversion with validation
- Structured error responses (400 Bad Request)
- Field-level error paths for UI integration

## Error Response Format

All frameworks return the same structured error format:

```json
{
  "code": "VALIDATION",
  "status": 400,
  "message": "Validation failed with 3 errors",
  "retryable": false,
  "details": {
    "fields": {
      "email": [
        {
          "code": "invalid_email",
          "message": "Invalid email format"
        }
      ],
      "rooms[0].adults": [
        {
          "code": "out_of_range",
          "message": "Must be between 1 and 4",
          "meta": {"min": "1", "max": "4"}
        }
      ],
      "rooms[1].children": [
        {
          "code": "out_of_range",
          "message": "Must be between 0 and 3",
          "meta": {"min": "0", "max": "3"}
        }
      ]
    }
  }
}
```

**Key features:**
- **`code`**: Machine-readable error code for programmatic handling
- **`message`**: Human-readable message for display
- **`meta`**: Additional context (validation limits, patterns, etc.)
- **Field paths**: Include array indices (`rooms[0].adults`) for precise UI targeting

## Axum Integration

### Installation

```toml
[dependencies]
domainstack-axum = "1.0"
domainstack = { version = "1.0", features = ["derive"] }
axum = "0.7"
```

### DomainJson Extractor

The recommended approach - validates during DTO→Domain conversion:

```rust
use axum::{routing::post, Router, Json};
use domainstack::prelude::*;
use domainstack_axum::{DomainJson, ErrorResponse};
use serde::Deserialize;

// DTO for deserialization
#[derive(Deserialize)]
struct CreateUserDto {
    name: String,
    email: String,
    age: u8,
}

// Domain type with validation
#[derive(Validate, serde::Serialize)]
struct User {
    #[validate(length(min = 2, max = 50))]
    name: String,

    #[validate(email)]
    email: String,

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

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

    fn try_from(dto: CreateUserDto) -> Result<Self, Self::Error> {
        let user = Self {
            name: dto.name,
            email: dto.email,
            age: dto.age,
        };
        user.validate()?;
        Ok(user)
    }
}

// Type alias for cleaner handlers
type CreateUserJson = DomainJson<User, CreateUserDto>;

async fn create_user(
    CreateUserJson { domain: user, .. }: CreateUserJson
) -> Result<Json<User>, ErrorResponse> {
    // user is GUARANTEED valid here!
    Ok(Json(user))
}

let app = Router::new().route("/users", post(create_user));
```

### ValidatedJson Extractor

For simpler cases where the DTO is your domain type:

```rust
use domainstack::Validate;
use domainstack_axum::ValidatedJson;

#[derive(Deserialize, Validate)]
struct QuickRequest {
    #[validate(length(min = 1, max = 100))]
    query: String,

    #[validate(range(min = 1, max = 100))]
    limit: u32,
}

async fn search(
    ValidatedJson(request): ValidatedJson<QuickRequest>
) -> Json<SearchResults> {
    // request is validated
    perform_search(request.query, request.limit).await
}
```

### Complete Axum Example

```rust
use axum::{
    routing::{get, post, put},
    Router, Json,
    extract::{Path, State},
};
use domainstack::prelude::*;
use domainstack_axum::{DomainJson, ErrorResponse};
use sqlx::PgPool;

// Types
type CreateBookingJson = DomainJson<Booking, CreateBookingDto>;
type UpdateBookingJson = DomainJson<UpdateBooking, UpdateBookingDto>;

// Handlers
async fn create_booking(
    State(db): State<PgPool>,
    CreateBookingJson { domain: booking, .. }: CreateBookingJson
) -> Result<Json<Booking>, ErrorResponse> {
    let saved = save_booking(&db, booking).await?;
    Ok(Json(saved))
}

async fn update_booking(
    State(db): State<PgPool>,
    Path(id): Path<i64>,
    UpdateBookingJson { domain: update, .. }: UpdateBookingJson
) -> Result<Json<Booking>, ErrorResponse> {
    let updated = update_booking_in_db(&db, id, update).await?;
    Ok(Json(updated))
}

// Router
let app = Router::new()
    .route("/bookings", post(create_booking))
    .route("/bookings/:id", put(update_booking))
    .with_state(db_pool);
```

**Full documentation:** [domainstack-axum README](../../domainstack-axum/README.md)

## Actix-web Integration

### Installation

```toml
[dependencies]
domainstack-actix = "1.0"
domainstack = { version = "1.0", features = ["derive"] }
actix-web = "4"
```

### DomainJson Extractor

```rust
use actix_web::{post, web, App, HttpServer};
use domainstack::prelude::*;
use domainstack_actix::{DomainJson, ErrorResponse};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUserDto {
    name: String,
    email: String,
    age: u8,
}

#[derive(Validate, serde::Serialize)]
struct User {
    #[validate(length(min = 2, max = 50))]
    name: String,

    #[validate(email)]
    email: String,

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

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

    fn try_from(dto: CreateUserDto) -> Result<Self, Self::Error> {
        let user = Self {
            name: dto.name,
            email: dto.email,
            age: dto.age,
        };
        user.validate()?;
        Ok(user)
    }
}

type UserJson = DomainJson<User, CreateUserDto>;

#[post("/users")]
async fn create_user(
    UserJson { domain: user, .. }: UserJson
) -> Result<web::Json<User>, ErrorResponse> {
    Ok(web::Json(user))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(create_user)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
```

### ValidatedJson Extractor

```rust
use domainstack::Validate;
use domainstack_actix::ValidatedJson;

#[derive(Deserialize, Validate)]
struct SearchRequest {
    #[validate(length(min = 1, max = 100))]
    query: String,
}

#[post("/search")]
async fn search(
    ValidatedJson(request): ValidatedJson<SearchRequest>
) -> web::Json<SearchResults> {
    web::Json(perform_search(request.query).await)
}
```

### Complete Actix-web Example

```rust
use actix_web::{web, App, HttpServer, post, put};
use domainstack::prelude::*;
use domainstack_actix::{DomainJson, ErrorResponse};
use sqlx::PgPool;

type CreateBookingJson = DomainJson<Booking, CreateBookingDto>;

#[post("/bookings")]
async fn create_booking(
    db: web::Data<PgPool>,
    CreateBookingJson { domain: booking, .. }: CreateBookingJson
) -> Result<web::Json<Booking>, ErrorResponse> {
    let saved = save_booking(&db, booking).await?;
    Ok(web::Json(saved))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let pool = PgPool::connect(&db_url).await.unwrap();

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(pool.clone()))
            .service(create_booking)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
```

**Note:** Actix extractor uses `block_on()` for synchronous validation in async context. This is the standard pattern for Actix-web 4.x extractors.

**Full documentation:** [domainstack-actix README](../../domainstack-actix/README.md)

## Rocket Integration

### Installation

```toml
[dependencies]
domainstack-rocket = "1.0"
domainstack = { version = "1.0", features = ["derive"] }
rocket = "0.5"
```

### DomainJson Request Guard

```rust
use rocket::{post, routes, serde::json::Json};
use domainstack::prelude::*;
use domainstack_rocket::{DomainJson, ErrorResponse};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUserDto {
    name: String,
    email: String,
    age: u8,
}

#[derive(Validate, serde::Serialize)]
struct User {
    #[validate(length(min = 2, max = 50))]
    name: String,

    #[validate(email)]
    email: String,

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

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

    fn try_from(dto: CreateUserDto) -> Result<Self, Self::Error> {
        let user = Self {
            name: dto.name,
            email: dto.email,
            age: dto.age,
        };
        user.validate()?;
        Ok(user)
    }
}

#[post("/users", data = "<user>")]
fn create_user(
    user: DomainJson<User, CreateUserDto>
) -> Result<Json<User>, ErrorResponse> {
    Ok(Json(user.domain))
}
```

### Error Catcher (Required)

Rocket requires an error catcher for proper error handling:

```rust
use rocket::{catch, catchers, Request};
use domainstack_rocket::ErrorResponse;

#[catch(400)]
fn validation_catcher(req: &Request) -> ErrorResponse {
    req.local_cache(|| None::<ErrorResponse>)
        .clone()
        .unwrap_or_else(|| {
            ErrorResponse(Box::new(error_envelope::Error::bad_request("Bad Request")))
        })
}

#[rocket::main]
async fn main() {
    rocket::build()
        .mount("/", routes![create_user])
        .register("/", catchers![validation_catcher])  // Required!
        .launch()
        .await
        .unwrap();
}
```

**Full documentation:** [domainstack-rocket README](../../domainstack-rocket/README.md)

## Framework Comparison

| Feature | Axum | Actix-web | Rocket |
|---------|------|-----------|--------|
| **DomainJson** | | | |
| **ValidatedJson** | | | |
| **Automatic ErrorResponse** | | | (needs catcher) |
| **Async Validation** | Native | ⚠️ `block_on()` | Native |
| **Setup Complexity** | Low | Low | Medium |
| **Type Safety** | High | High | High |

### When to Use Each

**Axum**: Modern, tower-based, excellent for new projects. Best async story.

**Actix-web**: Battle-tested, high performance. Uses `block_on()` for sync validation in async context.

**Rocket**: Developer-friendly, macro-heavy. Requires error catcher registration.

## Domain Modeling for HTTP

### DTO → Domain Pattern

```rust
// DTO: Public fields for deserialization
#[derive(Deserialize)]
pub struct CreateBookingDto {
    pub guest_email: String,
    pub check_in: String,
    pub check_out: String,
    pub rooms: Vec<RoomDto>,
}

// Domain: Private fields, business invariants
#[derive(Validate)]
#[validate(
    check = "self.check_out > self.check_in",
    message = "Check-out must be after check-in"
)]
pub struct Booking {
    #[validate(email)]
    guest_email: String,

    check_in: NaiveDate,
    check_out: NaiveDate,

    #[validate(min_items = 1, max_items = 5)]
    #[validate(each(nested))]
    rooms: Vec<Room>,
}

impl TryFrom<CreateBookingDto> for Booking {
    type Error = ValidationError;

    fn try_from(dto: CreateBookingDto) -> Result<Self, Self::Error> {
        // Parse dates
        let check_in = NaiveDate::parse_from_str(&dto.check_in, "%Y-%m-%d")
            .map_err(|_| ValidationError::single("check_in", "invalid_date", "Invalid date format"))?;

        let check_out = NaiveDate::parse_from_str(&dto.check_out, "%Y-%m-%d")
            .map_err(|_| ValidationError::single("check_out", "invalid_date", "Invalid date format"))?;

        // Convert rooms
        let rooms: Result<Vec<Room>, _> = dto.rooms
            .into_iter()
            .enumerate()
            .map(|(i, r)| Room::try_from(r).map_err(|e| e.prefixed(format!("rooms[{}]", i))))
            .collect();

        let booking = Self {
            guest_email: dto.guest_email,
            check_in,
            check_out,
            rooms: rooms?,
        };

        booking.validate()?;
        Ok(booking)
    }
}
```

### Type Aliases for Clean Handlers

```rust
// Define once
type CreateBookingJson = DomainJson<Booking, CreateBookingDto>;
type UpdateBookingJson = DomainJson<UpdateBooking, UpdateBookingDto>;
type CancelBookingJson = DomainJson<CancelBooking, CancelBookingDto>;

// Use in handlers
async fn create_booking(CreateBookingJson { domain: booking, .. }: CreateBookingJson) { ... }
async fn update_booking(UpdateBookingJson { domain: update, .. }: UpdateBookingJson) { ... }
async fn cancel_booking(CancelBookingJson { domain: cancel, .. }: CancelBookingJson) { ... }
```

## Error Customization

### Using error-envelope Directly

```rust
use domainstack_envelope::IntoEnvelopeError;

async fn create_user(
    Json(dto): Json<CreateUserDto>
) -> Result<Json<User>, ErrorResponse> {
    let user = User::try_from(dto)
        .map_err(|e| ErrorResponse::from(e.into_envelope_error()))?;

    Ok(Json(user))
}
```

### Custom Error Responses

```rust
use serde::Serialize;
use std::collections::BTreeMap;

#[derive(Serialize)]
struct ApiError {
    success: bool,
    errors: BTreeMap<String, Vec<FieldError>>,
}

#[derive(Serialize)]
struct FieldError {
    code: String,
    message: String,
}

fn to_api_error(err: ValidationError) -> ApiError {
    let mut errors = BTreeMap::new();

    for (path, violations) in err.field_violations_map() {
        let field_errors = violations.iter().map(|v| FieldError {
            code: v.code.to_string(),
            message: v.message.clone(),
        }).collect();

        errors.insert(path, field_errors);
    }

    ApiError { success: false, errors }
}
```

## Client-Side Error Handling

### TypeScript Interface

```typescript
interface ValidationErrorResponse {
  code: string;
  status: number;
  message: string;
  retryable: boolean;
  details: {
    fields: {
      [fieldPath: string]: Array<{
        code: string;
        message: string;
        meta?: Record<string, string>;
      }>;
    };
  };
}
```

### React Hook Form Integration

```typescript
import { useForm } from 'react-hook-form';

function BookingForm() {
  const { setError, handleSubmit } = useForm();

  const onSubmit = async (data: BookingFormData) => {
    try {
      await api.createBooking(data);
    } catch (error) {
      if (error.status === 400) {
        const response = error.data as ValidationErrorResponse;

        // Map errors to form fields
        for (const [path, errors] of Object.entries(response.details.fields)) {
          setError(path, {
            type: errors[0].code,
            message: errors[0].message,
          });
        }
      }
    }
  };

  return <form onSubmit={handleSubmit(onSubmit)}>...</form>;
}
```

### Handling Array Field Errors

```typescript
// Handle array indices in paths
function displayArrayErrors(path: string, errors: FieldError[]) {
  // path might be "rooms[0].adults" or "rooms[2].children"
  const match = path.match(/(\w+)\[(\d+)\]\.(\w+)/);

  if (match) {
    const [, arrayName, index, fieldName] = match;
    // Highlight specific item in array form
    highlightArrayItem(arrayName, parseInt(index), fieldName, errors);
  }
}
```

## Testing HTTP Endpoints

### Axum Testing

```rust
use axum::routing::post;
use axum_test::TestServer;

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

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

    response.assert_status_bad_request();

    let body: serde_json::Value = response.json();
    assert_eq!(body["code"], "VALIDATION");
    assert!(body["details"]["fields"]["name"].is_array());
    assert!(body["details"]["fields"]["email"].is_array());
    assert!(body["details"]["fields"]["age"].is_array());
}

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

    let response = server
        .post("/users")
        .json(&json!({
            "name": "Alice",
            "email": "alice@example.com",
            "age": 25
        }))
        .await;

    response.assert_status_ok();
}
```

### Actix-web Testing

```rust
use actix_web::{test, App};

#[actix_web::test]
async fn test_validation_error() {
    let app = test::init_service(App::new().service(create_user)).await;

    let req = test::TestRequest::post()
        .uri("/users")
        .set_json(&json!({
            "name": "",
            "email": "invalid",
            "age": 200
        }))
        .to_request();

    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), 400);
}
```

## See Also

- **Framework READMEs:**
  - [domainstack-axum]../../domainstack-axum/README.md - Full Axum documentation
  - [domainstack-actix]../../domainstack-actix/README.md - Full Actix-web documentation
  - [domainstack-rocket]../../domainstack-rocket/README.md - Full Rocket documentation

- **Related Guides:**
  - [Async Validation]ASYNC_VALIDATION.md - Database and API checks
  - [Error Handling]ERROR_HANDLING.md - Working with `ValidationError`
  - [Serde Integration]SERDE_INTEGRATION.md - Validate on deserialize
  - [Patterns]PATTERNS.md - DTO → Domain patterns