2.1 KiB
Compose Utilities
Purpose
The compose utilities provide functional combinators for working with validation results and schemas. mergeResults aggregates multiple ParseResult<T> values into a single ParseResult<T[]>, collecting all issues from failures. pipe composes a schema with one or more transform functions into a new pipeline schema, enabling clean left-to-right data transformation chains without manual wrapping.
Features
mergeResults<T>(results)— aggregate array of results, collecting all failurespipe<T, U>(schema, ...transforms)— compose schema with sequential transforms
Usage: Basic Example
import { pipe, string } from "@suaveplan/validation";
const trimmedLength = pipe(
string(),
(v: unknown) => (v as string).trim(),
(v: unknown) => (v as string).length,
);
trimmedLength.parse(" hello "); // 5
Usage: Advanced Example
import { mergeResults, number } from "@suaveplan/validation";
const n = number().min(0);
const results = [1, 2, -3, 4].map((v) => n.safeParse(v));
const merged = mergeResults(results);
// merged.success === false, merged.error.issues has one issue for -3
API Reference
mergeResults<T>(results: ParseResult<T>[]): ParseResult<T[]>
If all results are successes, returns { success: true, data: T[] }.
If any result is a failure, returns { success: false, error: ValidationError } with all issues aggregated from all failures.
pipe<T, U>(schema: BaseSchema<unknown, T>, ...transforms: TransformFn<unknown, unknown>[]): BaseSchema<unknown, U>
Chains schema with each transform in order using TransformSchema. Each transform receives the previous stage's output as unknown (type-cast by the caller). Returns a new schema producing type U.
Implementation Notes
mergeResultswith an empty array returns{ success: true, data: [] }.pipewith no transforms returns the original schema (zero iterations of the loop).- Transform functions in
pipeacceptunknownto avoid TypeScript variance issues across the chain; callers must cast appropriately.