Skip to main content

Module tower

Module tower 

Source
Expand description

§vld_web::tower — Tower middleware for vld

A tower::Layer that validates JSON request bodies against a vld schema, for any Tower service over the http types: an Axum Router (see examples/tower_axum.rs), a hyper service via hyper-util’s TowerToHyperService, or a plain service_fn. It depends only on tower-layer / tower-service / http, not on a web framework.

On success the validated value is stored in the request extensions as Validated<T> and the body bytes are forwarded. On failure a JSON error response is returned and the inner service is not called (see the error body format):

SituationStatus
schema validation failed / malformed JSON / body read error422
body larger than the limit (ValidateJsonLayer::with_limit, default 2 MiB)413

Requests whose Content-Type is not JSON (application/json or application/*+json, case-insensitive) are passed through untouched (body not read), so validated returns Option<T>.

The inner service receives Request<ValidatedBody<B>>: the buffered bytes for validated JSON requests, the original body otherwise. Responses are Response<ValidatedBody<ResBody>>: the error body or the inner service’s. The layer never fails itself; its error type is the inner service’s.

§Example

use bytes::Bytes;
use http::{Request, Response, StatusCode};
use http_body_util::Full;
use tower::{ServiceBuilder, ServiceExt};
use vld_web::tower::{validated, ValidateJsonLayer, ValidatedBody};

vld::schema! {
    #[derive(Debug, Clone)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

async fn handler(
    req: Request<ValidatedBody<Full<Bytes>>>,
) -> Result<Response<Full<Bytes>>, std::convert::Infallible> {
    let name = validated::<CreateUser>(&req).map_or("not JSON".into(), |u| u.name);
    Ok(Response::new(Full::new(Bytes::from(name))))
}

let svc = ServiceBuilder::new()
    .layer(ValidateJsonLayer::<CreateUser>::new())
    .service_fn(handler);

let req = Request::post("/users")
    .header("content-type", "application/json")
    .body(Full::new(Bytes::from(r#"{"name":"A","email":"bad"}"#)))
    .unwrap();
let resp = svc.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);

Guide: https://s00d.github.io/vld/integrations/web/tower

Modules§

prelude
Prelude — import everything you need.

Structs§

ValidateJsonLayer
A tower_layer::Layer that validates JSON request bodies with vld.
ValidateJsonService
The middleware Service created by ValidateJsonLayer.
Validated
The validated value, stored in the request extensions by ValidateJsonLayer (a wrapper, so it never collides with other extensions of type T).

Functions§

validated
Extract the validated value from request extensions.

Type Aliases§

ValidatedBody
Body type seen by the inner service (Left: the buffered bytes of a validated JSON request, Right: the untouched original body of a non-JSON request) and returned by the layer (Left: a JSON error body, Right: the inner service’s body).