$ cat docs/schema.md
Schema & validationSchema e validação
One contract: any Standard Schema v1 schema validates body, query, params and headers, and errors come out as RFC 9457.Um contrato só: qualquer schema Standard Schema v1 valida body, query, params e headers, e os erros saem em RFC 9457.
Route validationValidação na rota
Declare schema on the route; the app validates before the handler and the type of
ctx.body is inferred from the schema. @tupik/core depends on no validation library.
Declare schema na rota; o app valida antes do handler e o tipo de ctx.body é inferido
do schema. O @tupik/core não depende de nenhuma lib de validação.
Without a params schema, ctx.params is a Record<string, string>. Declare
one when you want a typed, validated id. A response schema cuts fields it does not declare
(createApp({ response }): 'strip' by default, 'validate' or 'off').
Data classes and the cut are explained in the security model.
Sem schema de params, ctx.params é um Record<string, string>. Declare um
quando quiser um id tipado e validado. Um schema de response corta os campos que ele não declara
(createApp({ response }): 'strip' por padrão, 'validate' ou 'off').
Classes de dado e o corte estão no modelo de segurança.
import { createApp, createModule } from '@tupik/core';
import { z } from 'zod'; // any Standard Schema v1 library (Zod, Valibot, ArkType…)
const users = createModule('/users').post('/', {
access: 'public',
schema: {
body: z.object({ name: z.string().min(1) }),
response: { 201: z.object({ name: z.string() }) },
},
handler: (ctx) => ctx.status(201).json({ name: ctx.body.name }),
});
export const app = createApp().register(users);import { createApp, createModule } from '@tupik/core';
import { z } from 'zod'; // qualquer lib Standard Schema v1 (Zod, Valibot, ArkType…)
const users = createModule('/users').post('/', {
access: 'public',
schema: {
body: z.object({ name: z.string().min(1) }),
response: { 201: z.object({ name: z.string() }) },
},
handler: (ctx) => ctx.status(201).json({ name: ctx.body.name }),
});
export const app = createApp().register(users); RFC 9457 errorsErros RFC 9457
Every invalid field is reported at once, with JSON Pointer paths.
Todos os campos inválidos são reportados de uma vez, com caminhos em JSON Pointer.
HTTP/1.1 400 Bad Request
content-type: application/problem+json; charset=utf-8
{
"type": "https://tupik.dev/problems/validation-error",
"title": "Validation failed",
"status": 400,
"detail": "The request contains 1 validation issue(s).",
"errors": [{ "pointer": "/body/name", "message": "..." }]
} Standalone validationValidação avulsa
validateSchema(schema, value) accepts sync or async validators; problemResponse and
toProblemDetails build the error document.
validateSchema(schema, valor) aceita validadores síncronos ou assíncronos;
problemResponse e toProblemDetails montam o documento de erro.
import { validateSchema, problemResponse } from '@tupik/schema';
const result = await validateSchema(nameSchema, input);
if (!result.success) {
return problemResponse(result.issues); // RFC 9457, status 400
}
console.log(result.value); Compiled serializerSerializer compilado
Standard Schema describes validation, not structure; that is why compileSerializer takes an explicit
shape and specializes property access once, with the same semantics as JSON.stringify.
Standard Schema descreve validação, não estrutura; por isso compileSerializer recebe um shape
explícito e especializa o acesso às propriedades uma vez, com a mesma semântica de JSON.stringify.
import { compileSerializer } from '@tupik/schema';
const toJson = compileSerializer({
type: 'object',
properties: {
id: { type: 'number' },
tags: { type: 'array', items: { type: 'string' } },
},
});
toJson({ id: 1, tags: ['a'] }); // '{"id":1,"tags":["a"]}'