在前端开发中,数据验证是非常重要的一个环节,能够有效地保证数据的正确性,避免程序运行时出现错误。在 Hapi 框架中,我们可以使用 Joi 这个强大的数据验证工具来进行数据验证。本文将为大家介绍如何在 Hapi 框架下使用 Joi 实现数据验证。
什么是 Joi
Joi 是一个用于 Node.js 的对象模式描述和验证库,它提供了一种简单、强大且可组合的方式来验证参数。Joi 可以用于验证任何类型的数据,包括字符串、数字、日期、布尔值等等。它还支持自定义验证函数和异步验证函数,能够满足各种复杂的验证需求。
安装 Joi
在使用 Joi 之前,我们需要先安装它。可以使用 npm 来安装 Joi,命令如下:
npm install joi
使用 Joi 进行数据验证
在 Hapi 框架中,我们可以使用 Joi 插件来进行数据验证。首先,我们需要在项目中引入 Joi 和 Hapi 插件:
// www.javascriptcn.com code example
const Joi = require('joi');
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register({
plugin: require('hapi-joi'),
options: {
joi: Joi
}
});
// ...
};在注册插件时,我们将 Joi 对象传递给 hapi-joi 插件,这样在之后就可以使用 Joi 进行数据验证了。
下面是一个简单的例子,使用 Joi 对请求参数进行验证:
// www.javascriptcn.com code example
const Joi = require('joi');
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register({
plugin: require('hapi-joi'),
options: {
joi: Joi
}
});
server.route({
method: 'GET',
path: '/hello/{name}',
handler: (request, h) => {
return `Hello ${request.params.name}!`;
},
options: {
validate: {
params: Joi.object({
name: Joi.string().required()
})
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();上面的例子中,我们定义了一个 GET 请求,路径为 /hello/{name},其中 {name} 是一个参数。使用 options.validate.params 来指定请求参数的验证规则。在这里,我们使用了 Joi.object() 来指定参数必须为一个对象,其中必须包含一个名为 name 的字符串属性。
如果请求参数不符合验证规则,Hapi 框架会返回一个 400 Bad Request 的错误响应。
自定义验证函数
有时候,我们需要对数据进行更复杂的验证,这时候可以使用自定义验证函数来实现。下面是一个例子,使用自定义验证函数来验证请求参数:
// www.javascriptcn.com code example
const Joi = require('joi');
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register({
plugin: require('hapi-joi'),
options: {
joi: Joi
}
});
const customValidator = (value, helpers) => {
if (value % 2 === 0) {
return value;
} else {
return helpers.error('any.invalid');
}
};
server.route({
method: 'GET',
path: '/even/{number}',
handler: (request, h) => {
return `The number ${request.params.number} is even!`;
},
options: {
validate: {
params: Joi.object({
number: Joi.number().custom(customValidator).required()
})
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();在这个例子中,我们定义了一个自定义验证函数 customValidator,它接收一个值和一个 helpers 对象作为参数。如果值是偶数,就返回该值;否则,调用 helpers.error('any.invalid') 来返回一个错误。
在路由的 options.validate.params 中,我们使用了 Joi.number().custom(customValidator) 来指定参数必须为一个数字,并且必须通过自定义验证函数 customValidator 的验证。
异步验证函数
有时候,我们需要对数据进行异步验证,这时候可以使用异步验证函数来实现。下面是一个例子,使用异步验证函数来验证请求参数:
// www.javascriptcn.com code example
const Joi = require('joi');
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register({
plugin: require('hapi-joi'),
options: {
joi: Joi
}
});
const asyncValidator = async (value, helpers) => {
const isValid = await new Promise((resolve) => {
setTimeout(() => {
resolve(value % 2 === 0);
}, 1000);
});
if (isValid) {
return value;
} else {
return helpers.error('any.invalid');
}
};
server.route({
method: 'GET',
path: '/even/{number}',
handler: (request, h) => {
return `The number ${request.params.number} is even!`;
},
options: {
validate: {
params: Joi.object({
number: Joi.number().custom(asyncValidator).required()
})
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();在这个例子中,我们定义了一个异步验证函数 asyncValidator,它接收一个值和一个 helpers 对象作为参数。我们使用 setTimeout 模拟一个耗时操作,1 秒后返回一个布尔值来表示验证结果。如果值是偶数,就返回该值;否则,调用 helpers.error('any.invalid') 来返回一个错误。
在路由的 options.validate.params 中,我们使用了 Joi.number().custom(asyncValidator) 来指定参数必须为一个数字,并且必须通过异步验证函数 asyncValidator 的验证。
结语
Joi 是一个非常强大的数据验证工具,能够满足各种复杂的验证需求。在 Hapi 框架中,我们可以使用 hapi-joi 插件来方便地使用 Joi 进行数据验证。希望本文对大家能够有所帮助,如有不足之处,欢迎指正。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/678b460a881faa801fa9216a