JSON Schema
Convert v.* validation schemas to JSON Schema 2020-12 with toJSONSchema(), the dialect of OpenAPI 3.1, and read the schemas a validate() middleware carries.
Every v.* schema in @axiljs/validation converts to JSON Schema 2020-12, the dialect of OpenAPI 3.1. The schema you validate requests with is the same one you publish, so an OpenAPI document, a typed client or a form builder never has to describe the input a second time.
Note
New in 0.4.0.
1import { toJSONSchema, v } from '@axiljs/validation'
2
3const createUser = v.object({
4 name: v.string().min(2).max(100),
5 email: v.string().email(),
6 age: v.number().integer().min(0).optional(),
7 role: v.enum(['admin', 'user']).default('user'),
8 bio: v.string().nullable()
9})
10
11createUser.toJSONSchema()
12// {
13// type: 'object',
14// properties: {
15// name: { type: 'string', minLength: 2, maxLength: 100 },
16// email: { type: 'string', format: 'email' },
17// age: { type: 'integer', minimum: 0 },
18// role: { type: 'string', enum: ['admin', 'user'], default: 'user' },
19// bio: { type: ['string', 'null'] }
20// },
21// required: ['name', 'email', 'bio']
22// }API
| Export | Description |
|---|---|
schema.toJSONSchema() | Method on every validator. Returns the JSON Schema of the input it accepts |
toJSONSchema(schema, options?) | Same as schema.toJSONSchema(); with { $schema: true } the root also gets $schema: JSON_SCHEMA_DIALECT |
JSON_SCHEMA_DIALECT | 'https://json-schema.org/draft/2020-12/schema' |
VALIDATION_SCHEMAS | Symbol.for('axiljs.validation.schemas'), the key under which validate() exposes its schemas |
| Types | JSONSchema, JSONSchemaType, ToJSONSchemaOptions, JSONSchemaConvertible |
1import { toJSONSchema, v } from '@axiljs/validation'
2
3toJSONSchema(v.string(), { $schema: true })
4// { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'string' }toJSONSchema() accepts anything with a toJSONSchema() method (JSONSchemaConvertible). Each call returns a new object.
Mapping
| Builder | JSON Schema |
|---|---|
v.string() | type: 'string' |
.min(n) / .max(n) on strings | minLength / maxLength |
.pattern(regex) | pattern: the regex source; flags (i, m, u, …) are dropped |
.email() / .url() | format: 'email' / format: 'uri' (email wins when both are set) |
v.number() | type: 'number', or type: 'integer' with .integer() |
.min(n) / .max(n) on numbers | minimum / maximum |
.positive() | exclusiveMinimum: 0 |
v.boolean() | type: 'boolean' |
v.enum([...]) | type: 'string', enum |
v.literal(x) | const: x with its type (string, boolean, integer, number; null for v.literal(null)) |
v.array(item) | type: 'array', items |
.min(n) / .max(n) on arrays | minItems / maxItems |
v.object(shape) | type: 'object', properties, required |
v.record(value) | type: 'object', additionalProperties: the value schema |
v.union([...]) | anyOf |
.optional() | Left out of the parent object's required |
.default(x) | default: x, and left out of the parent's required |
.nullable() | type: [T, 'null']; an enum gains null; a const or anyOf gains { type: 'null' } |
.custom(fn) / .transform(fn) | Nothing: not representable |
.trim() | Nothing; minLength / maxLength are emitted unchanged |
Examples of the less obvious cases:
1v.enum(['a', 'b']).nullable().toJSONSchema()
2// { type: ['string', 'null'], enum: ['a', 'b', null] }
3
4v.literal('x').nullable().toJSONSchema()
5// { anyOf: [{ type: 'string', const: 'x' }, { type: 'null' }] }
6
7v.union([v.string(), v.number()]).toJSONSchema()
8// { anyOf: [{ type: 'string' }, { type: 'number' }] }
9
10v.record(v.number()).toJSONSchema()
11// { type: 'object', additionalProperties: { type: 'number' } }
12
13v.number().positive().toJSONSchema()
14// { type: 'number', exclusiveMinimum: 0 }Input, not output
The JSON Schema describes the input a validator accepts, which is what a client must send:
.transform()changes the output ofparse()and is not reflected..custom()rules cannot be expressed and emit no constraint.v.number()andv.boolean()also accept numeric and boolean strings ('5','true'), because query strings and form fields are always text (see coercion). The schema still saysnumber/boolean: that is the type clients should send, and how a query parameter is documented in OpenAPI.- Objects accept keys they do not declare (kept by default, removed by
.strip()), soadditionalPropertiesis not set onv.object(). .trim()length limits apply to the trimmed value, which JSON Schema cannot express.
Discovering the schemas of validate()
The middleware returned by validate() carries the schemas it checks. Tools such as generateOpenAPI() in @axiljs/core use them to document a route without importing @axiljs/validation:
1import { validate, VALIDATION_SCHEMAS } from '@axiljs/validation'
2
3const mw = validate({ body: createUser, query: listQuery })
4
5mw.schemas.body // createUser
6mw[VALIDATION_SCHEMAS] // the same object as mw.schemas
7mw.schemas.body?.toJSONSchema() // JSON Schema of the body- Only the locations passed to
validate()(body,params,query) are present. - Both properties are read-only and non-enumerable, and the schemas object is frozen.
- Validation behaviour is unchanged. The returned middleware is typed as
ValidatedMiddleware.
OpenAPI explains how each location becomes path parameters, query parameters or a request body.
Related
- Schema builder: the
v.*builders and modifiers - Validation middleware:
validate({ body, params, query }) - OpenAPI: the document built from these schemas
- Generate a typed client: TypeScript types from the document
Was this page helpful?