docs: input validation via Standard Schema
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+65
-1
No files matched your search
@@ -369,6 +369,69 @@ const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
|
||||
|
||||
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
|
||||
|
||||
## 9. Validation
|
||||
|
||||
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
|
||||
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
|
||||
and others). green-tea's core has **zero runtime dependency** on any of them — bring
|
||||
whichever validator you already use:
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
import { Route, Post, body } from '@green-tea/core';
|
||||
|
||||
const CreateUser = z.object({ email: z.string().email() });
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Post('/')
|
||||
create(@body(CreateUser) user: { email: string }) {
|
||||
return { created: user.email };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The value the handler receives is the schema's **parsed/coerced output**, not the raw
|
||||
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
|
||||
parsed. Query strings are always strings on the wire, so a schema is often the coercion
|
||||
point:
|
||||
|
||||
```typescript
|
||||
const ListQuery = z.object({ page: z.coerce.number() });
|
||||
|
||||
@Get('/list')
|
||||
list(@query(ListQuery) q: { page: number }) {
|
||||
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
|
||||
}
|
||||
```
|
||||
|
||||
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
|
||||
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
|
||||
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
|
||||
> the whole parsed object (all of `body`/`query`/`headers`).
|
||||
|
||||
A failing schema short-circuits the request with **422**:
|
||||
|
||||
```json
|
||||
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
|
||||
```
|
||||
|
||||
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
|
||||
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
|
||||
|
||||
**Caveats:**
|
||||
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
|
||||
the same handler are not checked in that request.
|
||||
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
|
||||
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
|
||||
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
|
||||
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
|
||||
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
|
||||
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
|
||||
|
||||
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
|
||||
mesh remote-route validation are all out of scope for this feature.
|
||||
|
||||
## Inspect & test the graph
|
||||
|
||||
### Visualize with Mermaid
|
||||
|
||||
+2
-1
@@ -8,7 +8,7 @@ export type { GraphView } from './graph-viz';
|
||||
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
||||
export type { Plugin } from './plugin';
|
||||
export { JsonTransformer } from './transformers';
|
||||
export { HttpError, Unauthorized, NotFound, Redirect, NotModified } from './signals';
|
||||
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
|
||||
export { Bus } from './bus';
|
||||
export { flow, Flow } from './flow';
|
||||
export type { StepFn, CompiledFlow } from './flow';
|
||||
@@ -26,6 +26,7 @@ export type { MeshConfig } from './app';
|
||||
export type { RequestLimits } from './http';
|
||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||
export type { UploadedFile, MultipartBody } from './multipart';
|
||||
export type { StandardSchemaV1 } from './standard-schema';
|
||||
export { connectLink } from './mesh/link';
|
||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||
|
||||
Reference in new issue
Block a user