Initial Commit
This commit is contained in:
51
packages/foundation/data/validation/src/utils/compose.md
Normal file
51
packages/foundation/data/validation/src/utils/compose.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# 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 failures
|
||||
- `pipe<T, U>(schema, ...transforms)` — compose schema with sequential transforms
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```typescript
|
||||
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
|
||||
|
||||
```typescript
|
||||
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
|
||||
|
||||
- `mergeResults` with an empty array returns `{ success: true, data: [] }`.
|
||||
- `pipe` with no transforms returns the original schema (zero iterations of the loop).
|
||||
- Transform functions in `pipe` accept `unknown` to avoid TypeScript variance issues across the chain; callers must cast appropriately.
|
||||
Reference in New Issue
Block a user