Fastify 是一个高效且低开销的 Node.js Web 框架,它提供了快速的路由匹配和请求处理,同时还具有插件系统和可扩展性。AJV 是一个高度可配置的 JSON 校验器,它支持 JSON Schema Draft 7 和 Draft 2019-09,还具有优秀的性能和错误消息。在 Fastify 中使用 AJV 校验 JSON 数据可以有效地保证数据的正确性和可靠性,本文将详细介绍如何在 Fastify 中使用 AJV 校验 JSON 数据。
安装 AJV
首先需要在项目中安装 AJV,可以使用 npm 或 yarn 进行安装:
npm install ajv # 或者 yarn add ajv
创建 AJV 实例
创建一个 AJV 实例需要传入一些配置选项,例如:
// www.javascriptcn.com code example
const Ajv = require('ajv');
const ajv = new Ajv({
// 是否严格模式,启用后会禁用一些不安全或者不推荐的特性
strict: true,
// 是否缓存编译后的校验函数,启用后可以提高校验性能
cache: true,
// 是否允许使用 keywords,启用后可以使用一些扩展的关键字
allowKeywords: true,
// 是否启用 allErrors 模式,启用后会校验所有错误,而不是第一个错误
allErrors: false,
// 是否启用 verbose 模式,启用后会在错误消息中包含更多信息
verbose: false,
});这里介绍了一些常用的配置选项,具体可以参考 AJV 的文档。
定义 JSON Schema
在使用 AJV 校验 JSON 数据之前,需要先定义一个 JSON Schema,用于描述数据的结构和规则。JSON Schema 是一个基于 JSON 的数据格式,它定义了数据的类型、格式、约束和验证规则,可以用于校验和文档化 JSON 数据。
下面是一个简单的 JSON Schema 示例:
// www.javascriptcn.com code example
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 120
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name"]
}这个 JSON Schema 定义了一个包含 name、age 和 email 三个字段的对象,其中 name 是必填项,age 是一个介于 0 和 120 之间的整数,email 是一个符合 email 格式的字符串。可以根据实际需求定义更复杂的 JSON Schema。
编译校验函数
在使用 JSON Schema 校验 JSON 数据之前,需要先编译校验函数。AJV 可以将 JSON Schema 编译成一个校验函数,这个校验函数可以重复使用,提高校验性能。
下面是一个编译校验函数的示例:
// www.javascriptcn.com code example
const schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 120
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name"]
};
const validate = ajv.compile(schema);这里使用了之前定义的 JSON Schema,并通过 ajv.compile() 方法将其编译成一个校验函数 validate。
校验 JSON 数据
在编译了校验函数之后,就可以使用它来校验 JSON 数据了。AJV 校验函数接收一个 JSON 数据作为参数,返回一个布尔值,表示校验是否通过。
下面是一个校验 JSON 数据的示例:
// www.javascriptcn.com code example
const data = {
"name": "Alice",
"age": 18,
"email": "alice@example.com"
};
if (validate(data)) {
console.log('数据校验通过');
} else {
console.log('数据校验失败', validate.errors);
}这里使用了之前编译的校验函数 validate,并将一个包含 name、age 和 email 三个字段的对象作为参数传入。如果校验通过,就输出数据校验通过,否则输出数据校验失败,并打印错误信息。
在 Fastify 中使用 AJV
在 Fastify 中使用 AJV 校验 JSON 数据非常简单,只需要在路由处理函数中使用 AJV 校验函数即可。Fastify 还提供了一个 fastify-plugin 插件,可以方便地注册 AJV 插件。
下面是一个在 Fastify 中使用 AJV 校验 JSON 数据的示例:
// www.javascriptcn.com code example
const fastify = require('fastify')();
fastify.register(require('fastify-plugin'), async function (fastify, options) {
const Ajv = require('ajv');
const ajv = new Ajv({
// 配置选项
});
fastify.decorate('ajv', ajv);
});
fastify.post('/', async function (request, reply) {
const schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 120
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name"]
};
const validate = this.ajv.compile(schema);
const data = request.body;
if (validate(data)) {
reply.send({ message: '数据校验通过' });
} else {
reply.status(400).send({ message: '数据校验失败', errors: validate.errors });
}
});
fastify.listen(3000, function (err, address) {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening on ${address}`);
});这里使用 fastify-plugin 插件注册了一个 AJV 实例,然后在路由处理函数中使用了这个实例来编译和校验 JSON Schema。如果校验通过,就返回一个包含 message 字段的响应,否则返回一个带有错误信息的 400 响应。
结语
通过本文的介绍,相信大家已经了解了在 Fastify 中使用 AJV 校验 JSON 数据的方法。AJV 是一个非常强大的 JSON 校验器,它可以帮助我们保证数据的正确性和可靠性。在实际开发中,可以根据实际需求定义更复杂的 JSON Schema,以满足业务需求。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67961846504e4ea9bdc97645