Crate domainstack_rocket

Crate domainstack_rocket 

Source
Expand description

Rocket integration for domainstack validation

This crate provides Rocket request guards for automatic validation and domain conversion:

§Example

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

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

struct User {
    name: String,
    email: 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("email", dto.email.as_str(), &rules::email())?;
        validate("age", &dto.age, &rules::range(18, 120))?;
        Ok(Self { name: dto.name, email: dto.email, age: dto.age })
    }
}

#[post("/users", data = "<user>")]
fn create_user(user: DomainJson<User, CreateUserDto>) -> Result<Json<String>, ErrorResponse> {
    // user.domain is guaranteed valid here!
    Ok(Json(format!("Created user: {}", user.domain.name)))
}

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

Structs§

DomainJson
Request guard for domain type conversion with automatic validation
ErrorResponse
Structured error response for Rocket
ValidatedJson
Request guard for DTO validation without domain conversion