Schema 校验(JSON Schema)
Fastify 原生支持 JSON Schema 标准,允许你为请求参数和响应数据定义严格的结构规则,提升接口的健壮性与可维护性。
定义请求校验 Schema
你可以通过 schema 属性对请求的 body、params、querystring 和 headers 进行校验:
fastify.post('/user', {
schema: {
body: {
type: 'object',
required: ['name', 'email'],
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' },
age: { type: 'integer', minimum: 0 }
}
}
}
}, async (request) => {
return { status: 'ok' };
});
若客户端传入的数据不符合 Schema,Fastify 会自动返回 400 错误,并提供详细的错误信息。
校验路径参数和查询参数
fastify.get('/items/:id', {
schema: {
params: {
type: 'object',
properties: {
id: { type: 'string', pattern: '^[0-9]+$' }
},
required: ['id']
},
querystring: {
type: 'object',
properties: {
limit: { type: 'integer', minimum: 1, maximum: 100 }
}
}
}
}, async (request) => {
return { id: request.params.id };
});
定义响应 Schema
你还可以使用 response 字段为不同状态码下的响应定义 Schema:
fastify.get('/profile', {
schema: {
response: {
200: {
type: 'object',
properties: {
username: { type: 'string' },
email: { type: 'string' }
}
}
}
}
}, async () => {
return { username: 'tom', email: 'tom@example.com' };
});
如果返回的数据不符合 Schema,开发阶段会抛出异常,有助于快速发现错误。
复用 Schema
可通过外部变量或插件的方式复用 Schema:
const userSchema = {
type: 'object',
required: ['username'],
properties: {
username: { type: 'string' }
}
};
fastify.post('/login', {
schema: {
body: userSchema
}
}, async (request) => {
return { success: true };
});
Schema 编译器自定义
Fastify 允许替换默认的 JSON Schema 编译器(如使用 AJV 配置项):
const fastify = require('fastify')({
ajv: {
customOptions: {
allErrors: true,
removeAdditional: 'all'
}
}
});
相关内容
- Fastify 与 Express 对比 本节将对 Fastify 和 Express 两个流行的 Node.js 框架进行对比,帮助开发者理解它们的异同以及在不同场景下的选择。
- 中间件迁移指南 本节介绍如何在 Fastify 中迁移中间件,帮助开发者从其他框架(如 Express)迁移到 Fastify,理解 Fastify 中间件的工作方式,并学习如...
- 常用插件清单 本节列出了一些常用的 Fastify 插件,帮助开发者更好地扩展和定制 Fastify 应用。
- 核心 API 介绍 介绍 Fastify 中常用的核心 API,包括路由注册、请求与响应对象、日志等。
- Hello World 快速上手 Fastify,编写第一个 “Hello World” 应用,体验其简洁的 API 和高性能启动。
- 请求与响应对象 详解 Fastify 中的 request 和 reply 对象,用于获取请求信息和构造响应。