我目前正在创建一个API,用于使用nodejs在后台发布。从前端提供的我的数据对象包含多个对象。
我的第一步是检查这些多个常量是否为空,如果为空,它们会给出特定的错误消息,如下所示:
//constants
const { name, lang, email } = req.body;
if (!name) {
return res.status(400).json({
error_code: 1,
message: 'Missing name',
});
}
if (!lang) {
return res.status(400).json({
error_code: 2,
message: 'Lang not provided',
});
}
if (!email) {
return res.status(400).json({
error_code: 3,
message: 'email is not provided',
});
}
在上面的例子中,只有三个参数,但它如何寻找更多的常数?我想过做一个switch ... case
,但我不确定这是否是最好的解决方案,也不确定它会是什么样子。
你们有什么经验或建议吗?
考虑使用像ajv或joi这样的数据验证器库,它们是为此目的而设计的。
例如,有了joi,你可以有这样的东西:
const Joi = require('joi');
const schema = Joi.object({
name: Joi.string()
.min(3)
.max(30)
.required(),
lang: Joi.string()
.min(2)
.required(),
email: Joi.string()
.email({
minDomainSegments: 2,
tlds: {
allow: ['com', 'net', 'org']
}
})
})
// then in your controller you can have something like this
schema.validate(req.body);
// or this (I prefer this one)
try {
const value = await schema.validateAsync(req.body);
} catch (err) {
// do something
}