Skip to main content

验证和序列化

验证和序列化

¥Validation and Serialization

Fastify 使用基于模式的方法。我们建议使用 JSON 结构 来验证路由和序列化输出。Fastify 将模式编译为高性能函数。

¥Fastify uses a schema-based approach. We recommend using JSON Schema to validate routes and serialize outputs. Fastify compiles the schema into a highly performant function.

仅当内容类型为 application/json 时才会尝试验证。

¥Validation is only attempted if the content type is application/json.

所有示例都使用 JSON 架构草案 7 规范。

¥All examples use the JSON Schema Draft 7 specification.

⚠ 警告:将模式定义视为应用代码。验证和序列化功能使用 new Function(),这对于用户提供的架构来说是不安全的。有关详细信息,请参阅 Ajvfast-json-stringify

¥⚠ Warning: Treat schema definitions as application code. Validation and serialization features use new Function(), which is unsafe with user-provided schemas. See Ajv and fast-json-stringify for details.

虽然 Fastify 支持 $async Ajv 功能,但它不应用于初始验证。在验证期间访问数据库可能会导致拒绝服务攻击。验证后,使用 Fastify 的钩子preHandler 一样执行 async 任务。

¥Whilst Fastify supports the $async Ajv feature, it should not be used for initial validation. Accessing databases during validation may lead to Denial of Service attacks. Use Fastify's hooks like preHandler for async tasks after validation.

核心理念

¥Core concepts

验证和序列化由两个可自定义的依赖处理:

¥Validation and serialization are handled by two customizable dependencies:

这些依赖仅共享通过 .addSchema(schema) 添加到 Fastify 实例的 JSON 模式。

¥These dependencies share only the JSON schemas added to Fastify's instance via .addSchema(schema).

添加共享架构

¥Adding a shared schema

addSchema API 允许向 Fastify 实例添加多个模式,以便在整个应用中重用。此 API 已封装。

¥The addSchema API allows adding multiple schemas to the Fastify instance for reuse throughout the application. This API is encapsulated.

可以使用 JSON Schema $ref 关键字重用共享模式。以下是参考文献工作原理的概述:

¥Shared schemas can be reused with the JSON Schema $ref keyword. Here is an overview of how references work:

  • myField: { $ref: '#foo' } 在当前模式中搜索 $id: '#foo'

    ¥myField: { $ref: '#foo' } searches for $id: '#foo' in the current schema

  • myField: { $ref: '#/definitions/foo' } 在当前模式中搜索 definitions.foo

    ¥myField: { $ref: '#/definitions/foo' } searches for definitions.foo in the current schema

  • myField: { $ref: 'http://url.com/sh.json#' } 搜索与 $id: 'http://url.com/sh.json' 共享的模式

    ¥myField: { $ref: 'http://url.com/sh.json#' } searches for a shared schema with $id: 'http://url.com/sh.json'

  • myField: { $ref: 'http://url.com/sh.json#/definitions/foo' } 搜索与 $id: 'http://url.com/sh.json' 共享的模式并使用 definitions.foo

    ¥myField: { $ref: 'http://url.com/sh.json#/definitions/foo' } searches for a shared schema with $id: 'http://url.com/sh.json' and uses definitions.foo

  • myField: { $ref: 'http://url.com/sh.json#foo' } 搜索与 $id: 'http://url.com/sh.json' 共享的模式并在其中查找 $id: '#foo'

    ¥myField: { $ref: 'http://url.com/sh.json#foo' } searches for a shared schema with $id: 'http://url.com/sh.json' and looks for $id: '#foo' within it

简单用法:

¥Simple usage:

fastify.addSchema({
$id: 'http://example.com/',
type: 'object',
properties: {
hello: { type: 'string' }
}
})

fastify.post('/', {
handler () {},
schema: {
body: {
type: 'array',
items: { $ref: 'http://example.com#/properties/hello' }
}
}
})

$ref 作为根引用:

¥$ref as root reference:

fastify.addSchema({
$id: 'commonSchema',
type: 'object',
properties: {
hello: { type: 'string' }
}
})

fastify.post('/', {
handler () {},
schema: {
body: { $ref: 'commonSchema#' },
headers: { $ref: 'commonSchema#' }
}
})

检索共享模式

¥Retrieving the shared schemas

如果验证器和序列化器是自定义的,则 .addSchema 没有用,因为 Fastify 不再控制它们。要访问添加到 Fastify 实例的模式,请使用 .getSchemas()

¥If the validator and serializer are customized, .addSchema is not useful since Fastify no longer controls them. To access schemas added to the Fastify instance, use .getSchemas():

fastify.addSchema({
$id: 'schemaId',
type: 'object',
properties: {
hello: { type: 'string' }
}
})

const mySchemas = fastify.getSchemas()
const mySchema = fastify.getSchema('schemaId')

getSchemas 函数被封装并返回所选范围内可用的共享模式:

¥The getSchemas function is encapsulated and returns shared schemas available in the selected scope:

fastify.addSchema({ $id: 'one', my: 'hello' })
// will return only `one` schema
fastify.get('/', (request, reply) => { reply.send(fastify.getSchemas()) })

fastify.register((instance, opts, done) => {
instance.addSchema({ $id: 'two', my: 'ciao' })
// will return `one` and `two` schemas
instance.get('/sub', (request, reply) => { reply.send(instance.getSchemas()) })

instance.register((subinstance, opts, done) => {
subinstance.addSchema({ $id: 'three', my: 'hola' })
// will return `one`, `two` and `three`
subinstance.get('/deep', (request, reply) => { reply.send(subinstance.getSchemas()) })
done()
})
done()
})

验证

¥Validation

路由验证依赖于 Ajv v8,一种高性能 JSON 架构验证器。要验证输入,请将必填字段添加到路由模式中。

¥Route validation relies on Ajv v8, a high-performance JSON Schema validator. To validate input, add the required fields to the route schema.

支持的验证包括:

¥Supported validations include:

  • body:验证 POST、PUT 或 PATCH 方法的请求主体。

    ¥body: validates the request body for POST, PUT, or PATCH methods.

  • querystringquery:验证查询字符串。

    ¥querystring or query: validates the query string.

  • params:验证了路由参数。

    ¥params: validates the route parameters.

  • headers:验证请求标头。

    ¥headers: validates the request headers.

验证可以是完整的 JSON Schema 对象,其中 type'object''properties' 对象包含参数,也可以是更简单的变体,在顶层列出参数。

¥Validations can be a complete JSON Schema object with a type of 'object' and a 'properties' object containing parameters, or a simpler variation listing parameters at the top level.

ℹ 要使用最新的 Ajv (v8),请参阅 schemaController 部分。

¥ℹ For using the latest Ajv (v8), refer to the schemaController section.

示例:

¥Example:

const bodyJsonSchema = {
type: 'object',
required: ['requiredKey'],
properties: {
someKey: { type: 'string' },
someOtherKey: { type: 'number' },
requiredKey: {
type: 'array',
maxItems: 3,
items: { type: 'integer' }
},
nullableKey: { type: ['number', 'null'] }, // or { type: 'number', nullable: true }
multipleTypesKey: { type: ['boolean', 'number'] },
multipleRestrictedTypesKey: {
oneOf: [
{ type: 'string', maxLength: 5 },
{ type: 'number', minimum: 10 }
]
},
enumKey: {
type: 'string',
enum: ['John', 'Foo']
},
notTypeKey: {
not: { type: 'array' }
}
}
}

const queryStringJsonSchema = {
type: 'object',
properties: {
name: { type: 'string' },
excitement: { type: 'integer' }
}
}

const paramsJsonSchema = {
type: 'object',
properties: {
par1: { type: 'string' },
par2: { type: 'number' }
}
}

const headersJsonSchema = {
type: 'object',
properties: {
'x-foo': { type: 'string' }
},
required: ['x-foo']
}

const schema = {
body: bodyJsonSchema,
querystring: queryStringJsonSchema,
params: paramsJsonSchema,
headers: headersJsonSchema
}

fastify.post('/the/url', { schema }, handler)

对于 body 模式,可以通过将模式嵌套在 content 属性内来进一步区分每种内容类型的模式。将根据请求中的 Content-Type 标头应用架构验证。

¥For body schema, it is further possible to differentiate the schema per content type by nesting the schemas inside content property. The schema validation will be applied based on the Content-Type header in the request.

fastify.post('/the/url', {
schema: {
body: {
content: {
'application/json': {
schema: { type: 'object' }
},
'text/plain': {
schema: { type: 'string' }
}
// Other content types will not be validated
}
}
}
}, handler)

请注意,Ajv 将尝试将值 coerce 为模式 type 关键字中指定的类型,以通过验证并在之后使用正确类型的数据。

¥Note that Ajv will try to coerce values to the types specified in the schema type keywords, both to pass validation and to use the correctly typed data afterwards.

Fastify 中的 Ajv 默认配置支持在 querystring 中强制数组参数。示例:

¥The Ajv default configuration in Fastify supports coercing array parameters in querystring. Example:

const opts = {
schema: {
querystring: {
type: 'object',
properties: {
ids: {
type: 'array',
default: []
},
},
}
}
}

fastify.get('/', opts, (request, reply) => {
reply.send({ params: request.query }) // echo the querystring
})

fastify.listen({ port: 3000 }, (err) => {
if (err) throw err
})
curl -X GET "http://localhost:3000/?ids=1

{"params":{"ids":["1"]}}

可以为每种参数类型(主体、查询字符串、参数、标头)指定自定义架构验证器。

¥A custom schema validator can be specified for each parameter type (body, querystring, params, headers).

例如,以下代码仅对 body 参数禁用类型强制,从而更改 Ajv 默认选项:

¥For example, the following code disables type coercion only for the body parameters, changing the Ajv default options:

const schemaCompilers = {
body: new Ajv({
removeAdditional: false,
coerceTypes: false,
allErrors: true
}),
params: new Ajv({
removeAdditional: false,
coerceTypes: true,
allErrors: true
}),
querystring: new Ajv({
removeAdditional: false,
coerceTypes: true,
allErrors: true
}),
headers: new Ajv({
removeAdditional: false,
coerceTypes: true,
allErrors: true
})
}

server.setValidatorCompiler(req => {
if (!req.httpPart) {
throw new Error('Missing httpPart')
}
const compiler = schemaCompilers[req.httpPart]
if (!compiler) {
throw new Error(`Missing compiler for ${req.httpPart}`)
}
return compiler.compile(req.schema)
})

有关更多信息,请参阅 Ajv 强制

¥For more information, see Ajv Coercion.

Ajv 插件

¥Ajv Plugins

可以提供与默认 ajv 实例一起使用的插件列表。确保插件与 Fastify 中附带的 Ajv 版本兼容。

¥A list of plugins can be provided for use with the default ajv instance. Ensure the plugin is compatible with the Ajv version shipped within Fastify.

请参阅 ajv options 检查插件格式。

¥Refer to ajv options to check plugins format.

const fastify = require('fastify')({
ajv: {
plugins: [
require('ajv-merge-patch')
]
}
})

fastify.post('/', {
handler (req, reply) { reply.send({ ok: 1 }) },
schema: {
body: {
$patch: {
source: {
type: 'object',
properties: {
q: {
type: 'string'
}
}
},
with: [
{
op: 'add',
path: '/properties/q',
value: { type: 'number' }
}
]
}
}
}
})

fastify.post('/foo', {
handler (req, reply) { reply.send({ ok: 1 }) },
schema: {
body: {
$merge: {
source: {
type: 'object',
properties: {
q: {
type: 'string'
}
}
},
with: {
required: ['q']
}
}
}
}
})

验证器编译器

¥Validator Compiler

validatorCompiler 是一个返回函数以验证正文、URL 参数、标头和查询字符串的函数。默认的 validatorCompiler 返回一个实现 ajv 验证接口的函数。Fastify 在内部使用它来加快验证速度。

¥The validatorCompiler is a function that returns a function to validate the body, URL parameters, headers, and query string. The default validatorCompiler returns a function that implements the ajv validation interface. Fastify uses it internally to speed up validation.

Fastify 的 基线 ajv 配置 是:

¥Fastify's baseline ajv configuration is:

{
coerceTypes: 'array', // change data type of data to match type keyword
useDefaults: true, // replace missing properties and items with the values from corresponding default keyword
removeAdditional: true, // remove additional properties if additionalProperties is set to false, see: https://ajv.nodejs.cn/guide/modifying-data.html#removing-additional-properties
uriResolver: require('fast-uri'),
addUsedSchema: false,
// Explicitly set allErrors to `false`.
// When set to `true`, a DoS attack is possible.
allErrors: false
}

通过向 Fastify 工厂提供 ajv.customOptions 来修改基线配置。

¥Modify the baseline configuration by providing ajv.customOptions to the Fastify factory.

要更改或设置其他配置选项,请创建自定义实例并覆盖现有实例:

¥To change or set additional config options, create a custom instance and override the existing one:

const fastify = require('fastify')()
const Ajv = require('ajv')
const ajv = new Ajv({
removeAdditional: 'all',
useDefaults: true,
coerceTypes: 'array',
// any other options
// ...
})
fastify.setValidatorCompiler(({ schema, method, url, httpPart }) => {
return ajv.compile(schema)
})

🛈 注意:当使用自定义验证器实例时,请将架构添加到验证器而不是 Fastify。Fastify 的 addSchema 方法将无法识别自定义验证器。

¥🛈 Note: When using a custom validator instance, add schemas to the validator instead of Fastify. Fastify's addSchema method will not recognize the custom validator.

使用其他验证库

¥Using other validation libraries

setValidatorCompiler 函数允许用其他 JavaScript 验证库(如 joiyup)或自定义库替换 ajv

¥The setValidatorCompiler function allows substituting ajv with other JavaScript validation libraries like joi or yup, or a custom one:

const Joi = require('joi')

fastify.post('/the/url', {
schema: {
body: Joi.object().keys({
hello: Joi.string().required()
}).required()
},
validatorCompiler: ({ schema, method, url, httpPart }) => {
return data => schema.validate(data)
}
}, handler)
const yup = require('yup')
// Validation options to match ajv's baseline options used in Fastify
const yupOptions = {
strict: false,
abortEarly: false, // return all errors
stripUnknown: true, // remove additional properties
recursive: true
}

fastify.post('/the/url', {
schema: {
body: yup.object({
age: yup.number().integer().required(),
sub: yup.object().shape({
name: yup.string().required()
}).required()
})
},
validatorCompiler: ({ schema, method, url, httpPart }) => {
return function (data) {
// with option strict = false, yup `validateSync` function returns the
// coerced value if validation was successful, or throws if validation failed
try {
const result = schema.validateSync(data, yupOptions)
return { value: result }
} catch (e) {
return { error: e }
}
}
}
}, handler)
.statusCode 属性

¥.statusCode property

所有验证错误的 .statusCode 属性都设置为 400,确保默认错误处理程序将响应状态代码设置为 400

¥All validation errors have a .statusCode property set to 400, ensuring the default error handler sets the response status code to 400.

fastify.setErrorHandler(function (error, request, reply) {
request.log.error(error, `This error has status code ${error.statusCode}`)
reply.status(error.statusCode).send(error)
})
使用其他验证库的验证消息

¥Validation messages with other validation libraries

Fastify 的验证错误消息与默认验证引擎紧密耦合:从 ajv 返回的错误最终通过 schemaErrorFormatter 函数运行,该函数会构建人性化的错误消息。但是,schemaErrorFormatter 函数是在考虑 ajv 的情况下编写的。使用其他验证库时,这可能会导致奇怪或不完整的错误消息。

¥Fastify's validation error messages are tightly coupled to the default validation engine: errors returned from ajv are eventually run through the schemaErrorFormatter function which builds human-friendly error messages. However, the schemaErrorFormatter function is written with ajv in mind. This may result in odd or incomplete error messages when using other validation libraries.

要规避此问题,有两个主要选项:

¥To circumvent this issue, there are two main options:

  1. 确保验证函数(由自定义 schemaCompiler 返回)以与 ajv 相同的结构和格式返回错误。

    ¥Ensure the validation function (returned by the custom schemaCompiler) returns errors in the same structure and format as ajv.

  2. 使用自定义 errorHandler 拦截和格式化自定义验证错误。

    ¥Use a custom errorHandler to intercept and format custom validation errors.

Fastify 为所有验证错误添加了两个属性,以帮助编写自定义 errorHandler

¥Fastify adds two properties to all validation errors to help write a custom errorHandler:

  • validation:验证函数返回的对象的 error 属性的内容(由自定义 schemaCompiler 返回)

    ¥validation: the content of the error property of the object returned by the validation function (returned by the custom schemaCompiler)

  • validationContext:发生验证错误的上下文(主体、参数、查询、标头)

    ¥validationContext: the context (body, params, query, headers) where the validation error occurred

下面显示了一个处理验证错误的自定义 errorHandler 的虚构示例:

¥A contrived example of such a custom errorHandler handling validation errors is shown below:

const errorHandler = (error, request, reply) => {
const statusCode = error.statusCode
let response

const { validation, validationContext } = error

// check if we have a validation error
if (validation) {
response = {
// validationContext will be 'body', 'params', 'headers', or 'query'
message: `A validation error occurred when validating the ${validationContext}...`,
// this is the result of the validation library...
errors: validation
}
} else {
response = {
message: 'An error occurred...'
}
}

// any additional work here, eg. log error
// ...

reply.status(statusCode).send(response)
}

序列化

¥Serialization

如果路由选项中提供了输出模式,Fastify 使用 fast-json-stringify 以 JSON 形式发送数据。使用输出模式可以大大提高吞吐量并有助于防止意外泄露敏感信息。

¥Fastify uses fast-json-stringify to send data as JSON if an output schema is provided in the route options. Using an output schema can drastically increase throughput and help prevent accidental disclosure of sensitive information.

示例:

¥Example:

const schema = {
response: {
200: {
type: 'object',
properties: {
value: { type: 'string' },
otherValue: { type: 'boolean' }
}
}
}
}

fastify.post('/the/url', { schema }, handler)

响应模式基于状态代码。要对多个状态代码使用相同的模式,请使用 '2xx'default,例如:

¥The response schema is based on the status code. To use the same schema for multiple status codes, use '2xx' or default, for example:

const schema = {
response: {
default: {
type: 'object',
properties: {
error: {
type: 'boolean',
default: true
}
}
},
'2xx': {
type: 'object',
properties: {
value: { type: 'string' },
otherValue: { type: 'boolean' }
}
},
201: {
// the contract syntax
value: { type: 'string' }
}
}
}

fastify.post('/the/url', { schema }, handler)

可以为不同的内容类型定义特定的响应架构。例如:

¥A specific response schema can be defined for different content types. For example:

const schema = {
response: {
200: {
description: 'Response schema that support different content types'
content: {
'application/json': {
schema: {
name: { type: 'string' },
image: { type: 'string' },
address: { type: 'string' }
}
},
'application/vnd.v1+json': {
schema: {
type: 'array',
items: { $ref: 'test' }
}
}
}
},
'3xx': {
content: {
'application/vnd.v2+json': {
schema: {
fullName: { type: 'string' },
phone: { type: 'string' }
}
}
}
},
default: {
content: {
// */* is match-all content-type
'*/*': {
schema: {
desc: { type: 'string' }
}
}
}
}
}
}

fastify.post('/url', { schema }, handler)

串行器编译器

¥Serializer Compiler

serializerCompiler 返回一个必须从输入对象返回字符串的函数。定义响应 JSON 模式时,通过提供序列化每个路由的函数来更改默认序列化方法。

¥The serializerCompiler returns a function that must return a string from an input object. When defining a response JSON Schema, change the default serialization method by providing a function to serialize each route.

fastify.setSerializerCompiler(({ schema, method, url, httpStatus, contentType }) => {
return data => JSON.stringify(data)
})

fastify.get('/user', {
handler (req, reply) {
reply.send({ id: 1, name: 'Foo', image: 'BIG IMAGE' })
},
schema: {
response: {
'2xx': {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' }
}
}
}
}
})

要在代码的特定部分设置自定义序列化程序,请使用 reply.serializer(...)

¥To set a custom serializer in a specific part of the code, use reply.serializer(...).

错误处理

¥Error Handling

当请求的架构验证失败时,Fastify 将自动返回状态 400 响应,其中包括负载中验证器的结果。例如,如果以下架构用于路由:

¥When schema validation fails for a request, Fastify will automatically return a status 400 response including the result from the validator in the payload. For example, if the following schema is used for a route:

const schema = {
body: {
type: 'object',
properties: {
name: { type: 'string' }
},
required: ['name']
}
}

如果请求无法满足模式,则路由将返回具有以下有效负载的响应:

¥If the request fails to satisfy the schema, the route will return a response with the following payload:

{
"statusCode": 400,
"error": "Bad Request",
"message": "body should have required property 'name'"
}

要处理路由内的错误,请指定 attachValidation 选项。如果存在验证错误,则请求的 validationError 属性将包含带有原始验证结果的 Error 对象,如下所示:

¥To handle errors inside the route, specify the attachValidation option. If there is a validation error, the validationError property of the request will contain the Error object with the raw validation result as shown below:

const fastify = Fastify()

fastify.post('/', { schema, attachValidation: true }, function (req, reply) {
if (req.validationError) {
// `req.validationError.validation` contains the raw validation error
reply.code(400).send(req.validationError)
}
})

schemaErrorFormatter

要格式化错误,请在实例化 Fastify 时提供一个同步函数,该函数将错误作为 schemaErrorFormatter 选项返回。上下文函数将是 Fastify 服务器实例。

¥To format errors, provide a sync function that returns an error as the schemaErrorFormatter option when instantiating Fastify. The context function will be the Fastify server instance.

errors 是 Fastify 模式错误 FastifySchemaValidationError 的数组。dataVar 是当前已验证的模式部分(参数、主体、查询字符串、标头)。

¥errors is an array of Fastify schema errors FastifySchemaValidationError. dataVar is the currently validated part of the schema (params, body, querystring, headers).

const fastify = Fastify({
schemaErrorFormatter: (errors, dataVar) => {
// ... my formatting logic
return new Error(myErrorMessage)
}
})

// or
fastify.setSchemaErrorFormatter(function (errors, dataVar) {
this.log.error({ err: errors }, 'Validation failed')
// ... my formatting logic
return new Error(myErrorMessage)
})

使用 setErrorHandler 定义验证错误的自定义响应,例如:

¥Use setErrorHandler to define a custom response for validation errors such as:

fastify.setErrorHandler(function (error, request, reply) {
if (error.validation) {
reply.status(422).send(new Error('validation failed'))
}
})

有关架构中的自定义错误响应,请参阅 ajv-errors。查看 example 用法。

¥For custom error responses in the schema, see ajv-errors. Check out the example usage.

安装 ajv-errors 的 1.0.1 版本,因为后续版本与 AJV v6(Fastify v3 附带的版本)不兼容。

¥Install version 1.0.1 of ajv-errors, as later versions are not compatible with AJV v6 (the version shipped by Fastify v3).

以下是一个例子,展示了如何通过提供自定义 AJV 选项为模式的每个属性添加自定义错误消息。模式中的内联注释描述了如何配置它以针对每种情况显示不同的错误消息:

¥Below is an example showing how to add custom error messages for each property of a schema by supplying custom AJV options. Inline comments in the schema describe how to configure it to show a different error message for each case:

const fastify = Fastify({
ajv: {
customOptions: {
jsonPointers: true,
// ⚠ Warning: Enabling this option may lead to this security issue https://www.cvedetails.com/cve/CVE-2020-8192/
allErrors: true
},
plugins: [
require('ajv-errors')
]
}
})

const schema = {
body: {
type: 'object',
properties: {
name: {
type: 'string',
errorMessage: {
type: 'Bad name'
}
},
age: {
type: 'number',
errorMessage: {
type: 'Bad age', // specify custom message for
min: 'Too young' // all constraints except required
}
}
},
required: ['name', 'age'],
errorMessage: {
required: {
name: 'Why no name!', // specify error message for when the
age: 'Why no age!' // property is missing from input
}
}
}
}

fastify.post('/', { schema, }, (request, reply) => {
reply.send({
hello: 'world'
})
})

要返回本地化错误消息,请参阅 ajv-i18n

¥To return localized error messages, see ajv-i18n.

const localize = require('ajv-i18n')

const fastify = Fastify()

const schema = {
body: {
type: 'object',
properties: {
name: {
type: 'string',
},
age: {
type: 'number',
}
},
required: ['name', 'age'],
}
}

fastify.setErrorHandler(function (error, request, reply) {
if (error.validation) {
localize.ru(error.validation)
reply.status(400).send(error.validation)
return
}
reply.send(error)
})

JSON 模式支持

¥JSON Schema support

JSON Schema 提供实用程序来优化模式。结合 Fastify 的共享模式,所有模式都可以轻松重用。

¥JSON Schema provides utilities to optimize schemas. Combined with Fastify's shared schema, all schemas can be easily reused.

使用案例验证器串行器
$ref$id️️ ✔️✔️
$ref/definitions✔️✔️
$ref 到共享模式 $id✔️✔️
$ref 到共享模式 /definitions✔️✔️

示例

¥Examples

在同一 JSON 架构中使用 $ref$id

¥Usage of $ref to $id in same JSON Schema

const refToId = {
type: 'object',
definitions: {
foo: {
$id: '#address',
type: 'object',
properties: {
city: { type: 'string' }
}
}
},
properties: {
home: { $ref: '#address' },
work: { $ref: '#address' }
}
}
在同一 JSON 架构中使用 $ref/definitions

¥Usage of $ref to /definitions in same JSON Schema

const refToDefinitions = {
type: 'object',
definitions: {
foo: {
$id: '#address',
type: 'object',
properties: {
city: { type: 'string' }
}
}
},
properties: {
home: { $ref: '#/definitions/foo' },
work: { $ref: '#/definitions/foo' }
}
}
使用 $ref 到共享架构 $id 作为外部架构

¥Usage $ref to a shared schema $id as external schema

fastify.addSchema({
$id: 'http://foo/common.json',
type: 'object',
definitions: {
foo: {
$id: '#address',
type: 'object',
properties: {
city: { type: 'string' }
}
}
}
})

const refToSharedSchemaId = {
type: 'object',
properties: {
home: { $ref: 'http://foo/common.json#address' },
work: { $ref: 'http://foo/common.json#address' }
}
}
使用 $ref 到共享架构 /definitions 作为外部架构

¥Usage $ref to a shared schema /definitions as external schema

fastify.addSchema({
$id: 'http://foo/shared.json',
type: 'object',
definitions: {
foo: {
type: 'object',
properties: {
city: { type: 'string' }
}
}
}
})

const refToSharedSchemaDefinitions = {
type: 'object',
properties: {
home: { $ref: 'http://foo/shared.json#/definitions/foo' },
work: { $ref: 'http://foo/shared.json#/definitions/foo' }
}
}

资源

¥Resources