Skip to content

Pipes

Stateless transforms at the request boundary — parse, normalize, validate before the handler runs.

A pipe runs between extraction and the handler. The transport pulls a value out of the request — a path segment, a query param, a JSON body, a GraphQL argument, a WS payload, an MCP tool’s arguments, a queued job — and hands it to the pipe. The pipe either returns the transformed value, or rejects with a PipeError the transport renders as its native error.

Validation needs no pipe at all: every edge holds each argument it decoded to the rules its type declares, before any pipe runs, with nothing to wrap.

The trait lives in nest-rs-pipes, transport-agnostic, and binds per argument on every transport through one carrier, nest_rs::pipes::Piped:

  • HTTP names the extractor the pipe reads: Piped<P, Path<String>> runs P over what Path extracted.
  • GraphQL, WebSockets, MCP and queues decode the argument themselves, so the carrier is Piped<P> and the wire value is the pipe’s In — see Pipes beyond HTTP.

On every edge Piped(value) binds the pipe’s output.

nest_rs::pipes::Pipe
pub trait Pipe {
type In;
type Out;
fn transform(input: Self::In) -> Result<Self::Out, PipeError>;
}
Terminal window
cargo add nest-rs --features pipes

The http feature turns this on, and http is a default — name it explicitly only in a headless app built with default-features = false, where no transport implies it.

A pipe is a zero-sized marker named at a call site — never instantiated, never injected. transform is an associated function; there’s no &self and no DI container in scope. That’s deliberate: a pipe is a pure transform, the same input always produces the same output, and the type name is enough to pick which one runs.

crates/features/src/pipes/trim.rs
use nest_rs::pipes::{Pipe, PipeError};
pub struct Trim;
impl Pipe for Trim {
type In = String;
type Out = String;
fn transform(input: String) -> Result<String, PipeError> {
Ok(input.trim().to_string())
}
}

If you need DI-injected logic at the request boundary, that’s a service, an interceptor, or a global pipe — not a per-argument pipe.

nest-rs-pipes ships the common cases. Reach for them before writing your own:

PipeIn → OutUse it for
Parse<T>String → T (any FromStr)Generic conversion: ParseInt, ParseFloat, ParseBool
ParseUuidString → UuidAny-version UUID
ParseUuidV4 / ParseUuidV7 / …String → UuidVersion-pinned UUID
ParseArray<T>String → Vec<T> (any FromStr)Comma-separated list; a refused item is named by its position (item 2 must be a valid u64), never quoted
Trim, Lowercase, UppercaseString → StringEdge normalization

A PipeError rejection surfaces as the edge’s native error — on HTTP an RFC 9457 problem+json 400 — and the handler body never runs; each edge’s form is on Pipes beyond HTTP.

A type that declares validator rules is checked wherever it is decoded. #[input] carries the Validate derive, so the rules on the DTO are the whole declaration:

crates/features/src/users/http/controller.rs
use nest_rs::http::{Created, Json, Result};
use nest_rs::core::{Secret, input};
#[input]
pub struct CreateUser {
#[validate(email)]
email: String,
#[validate(length(min = 8))]
#[schemars(with = "String")]
password: Secret<String>,
}
#[post("/")]
async fn create(&self, Json(input): Json<CreateUser>) -> Result<Created<Json<User>>> {
let user = self.svc.create(input).await?;
Ok(Created::at(user.id, Json(User::from(&user))))
}

A password is a Secret from the moment it is decoded: its rules judge the value, and whatever serializes the DTO writes <redacted>. A Secret has no schema of its own, so #[schemars(with = "String")] names what the wire carries.

A rule of your own is a function custom(function = "…") names, returning nest_rs::pipes::validator::ValidationError, the error of the release the framework derives with.

The handler sees a validated CreateUser, and answers 201 with the new user’s Location, as responses teaches. Json, Query, Form, Path and Header answer for the value they carry, a list for each item and an Option for the value it holds. A malformed JSON body is 400 before the rules run. A well-formed body that breaks them is an RFC 9457 problem+json 400 with:

{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "validation failed",
"code": "INVALID_ARGUMENT",
"errors": {
"email": [{ "code": "email" }],
"password": [{ "code": "length" }]
}
}

A failure names its field and its rule, never the rule’s parameters: they hold what was sent (value, and must_match’s other field), and a bound such as max = self.limit can read another field. A rule that should tell the client its bound says so in its message. No manual checks in the handler.

The check runs after the guards and the class gate, so a caller they refuse pays for no validation and never learns what a valid input looks like. A service that builds an input itself — from a provider’s profile, from a seed — calls validate() on it, and converts the failure with PipeError::from when it answers through an edge’s pipe_error.

When the input needs a transform, name the pipe at the call site:

crates/features/src/users/http/controller.rs
use nest_rs::http::Path;
use nest_rs::pipes::{ParseUuidV7, Piped};
use nest_rs::http::Json;
#[get("/{id}")]
async fn get(&self, Piped(id): Piped<ParseUuidV7, Path<String>>) -> Result<Json<User>> {
Ok(Json(self.svc.find(id).await?))
}

Path<String> extracts the raw segment; ParseUuidV7::transform validates it as a v7 UUID. A non-UUID string is 400 with "must be a valid UUID", a UUID of another version 400 with "must be a UUID v7" — not a stringly-typed handler doing its own parse::<Uuid>(). Piped(id) binds the pipe’s output, a Uuid; the carrier also derefs to it.

The carrier is read where it is written: #[routes] takes Piped<P, E> spelled out in the handler’s signature, holds what E extracted to its rules, then runs the pipe. Piped is no extractor, so the same carrier behind a type alias does not compile rather than skip those rules.

A pipe bound per argument runs where its argument is decoded. One that shapes every input of the app at once — a body, a GraphQL operation’s variables, a WebSocket message’s data — is a global pipe, registered in main.

A pipe converts a primitive input — an ID string into a Uuid, a list into its items. A route declaring #[authorize(A, bind = S)] goes further: it parses the id, loads the row through a service, and authorizes it — returning 404 if the row doesn’t exist within the caller’s scope, 403 if denied.

crates/features/src/users/http/controller.rs
// Pipe — pure conversion, no DB
#[get("/_validate/{id}")]
async fn validate(&self, Piped(id): Piped<ParseUuidV7, Path<String>>) -> String {
format!("{id} is valid")
}
// Bound — convert + load + authorize
#[get("/{id}")]
#[authorize(Read, bind = UsersService)]
async fn get(&self, user: Authorized<Read, UserEntity>) -> Json<User> {
Json(User::from(&*user))
}

A bound subject depends on the data layer, and GraphQL takes the same attribute (see By-id binding). A pipe is transport-agnostic — the same ParseUuidV7 binds identically on HTTP, GraphQL, WebSockets, and queues.

Three rules:

  1. Stateless. transform is an associated function; no &self, no container.
  2. One file per pipe under crates/nest-rs-pipes/src/pipes/ (one role, one file). Reusable pipes belong to the framework crate — never to an app.
  3. Use the error envelope. Return PipeError::new(msg) for a simple message, PipeError::with_details(msg, details) to carry structured field-level errors.
crates/features/src/pipes/non_empty.rs
use nest_rs::pipes::{Pipe, PipeError};
pub struct NonEmpty;
impl Pipe for NonEmpty {
type In = String;
type Out = String;
fn transform(input: String) -> Result<String, PipeError> {
if input.trim().is_empty() {
Err(PipeError::new("must not be empty"))
} else {
Ok(input)
}
}
}

Then bind it at the call site:

crates/features/src/users/http/controller.rs
#[post("/")]
async fn create(&self, Piped(name): Piped<NonEmpty, Json<String>>) -> &'static str {
"ok"
}
  • HTTP / controllers — every extractor that composes with a pipe.
  • Pipes beyond HTTP — the same pipes on GraphQL, WebSockets, MCP and queues.
  • Global pipes — one pipe over every body, set of variables and message.
  • Guards — gate access; pipes don’t.
  • By-id binding — pipes are for primitives, bind = Service loads and authorizes a row.
  • sign_in/http/controller.rs in the demo — binds Piped<Lowercase, Path<String>> so the OAuth provider segment is case-insensitive.