@ fastify/ 应答- 验证
一个简单的插件,可以进行快速化的响应验证. 这个插件的使用会降低你的整体性能,因此我们建议只在开发期间使用.
安装
npm i @fastify/response-validation
使用量
您只需要注册插件, 并启用响应验证 :
import fastify from 'fastify'
const app = fastify()
await app.register(require('@fastify/response-validation'))
app.route({
method: 'GET',
path: '/',
schema: {
response: {
'2xx': {
type: 'object',
properties: {
answer: { type: 'number' }
}
}
}
},
handler: async (req, reply) => {
return { answer: '42' }
}
})
app.inject({
method: 'GET',
path: '/'
}, (err, res) => {
if (err) throw err
console.log(res.payload)
})
不同内容类型的答复得到 @fastify/response-validation, (中文(简体) ), @fastify/swagger,以及 fastify请使用 content 对于响应,否则将无法快速化,无法汇编计划:
{
response: {
200: {
description: 'Description and all status-code based properties are working',
content: {
'application/json': {
schema: {
name: { type: 'string' },
image: { type: 'string' },
address: { type: 'string' }
}
},
'application/vnd.v1+json': {
schema: {
fullName: { type: 'string' },
phone: { type: 'string' }
}
}
}
}
}
}
如果您想要推翻默认 页:1 配置,您可以通过使用 ajv 选项 :
// Default configuration:
// coerceTypes: false
// useDefaults: true
// removeAdditional: true
// allErrors: true
import responseValidator from '@fastify/response-validation'
// ... App setup
await fastify.register(responseValidator, {
ajv: {
coerceTypes: true
}
})
您也可以通过 ajv 实例
// Default configuration:
// coerceTypes: false
// useDefaults: true
// removeAdditional: true
// allErrors: true
import responseValidator from '@fastify/response-validation'
import Ajv from 'ajv'
// ... App setup
const ajv = new Ajv()
await fastify.register(responseValidator, { ajv })
默认情况下,在每个定义了响应策略的路径上都启用了响应验证. 如果需要的话,您可以一起禁用 responseValidation: false数字 :
import responseValidator from '@fastify/response-validation'
// ... App setup
await fastify.register(responseValidator, {
responseValidation: false
})
或者,您可以禁用同一选项的特定路径 :
fastify.route({
method: 'GET',
path: '/',
responseValidation: false,
schema: {
response: {
'2xx': {
type: 'object',
properties: {
answer: { type: 'number' }
}
}
}
},
handler: async (req, reply) => {
return { answer: '42' }
}
})
插件
您也可以通过添加新的 ajv 插件来扩展嵌入在此验证符中的 ajv 实例的功能 .
fastify.register(require('fastify-response-validation'), {
ajv: {
plugins: [
require('ajv-formats'),
[require('ajv-errors'), { singleError: false }]
// Usage: [plugin, pluginOptions] - Plugin with options
// Usage: plugin - Plugin without options
]
}
})
错误
此插件出错为 :
-
FST_RESPONSE_VALIDATION_FAILED_VALIDATION: 当答复不符合所提供的计划时, 就会发出这个错误 . -
FST_RESPONSE_VALIDATION_SCHEMA_NOT_DEFINED: 当没有JSON schema可用以验证响应时, 此错误会被释放 .