rok*_*rok 5 rest mongoose node.js koa joi
我正在使用Node.js,Mongoose和Koa开发RESTful API,并且对于模式和输入验证的最佳实践有些困惑。
目前,我对每种资源都有Mongoose和Joi模式。猫鼬模式仅包含有关特定资源的基本信息。例:
const UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
},
firstName: String,
lastName: String,
phone: String,
city: String,
state: String,
country: String,
});
Run Code Online (Sandbox Code Playgroud)
Joi模式包含有关对象的每个属性的详细信息:
{
email: Joi.string().email().required(),
firstName: Joi.string().min(2).max(50).required(),
lastName: Joi.string().min(2).max(50).required(),
phone: Joi.string().min(2).max(50).required(),
city: Joi.string().min(2).max(50).required(),
state: Joi.string().min(2).max(50).required(),
country: Joi.string().min(2).max(50).required(),
}
Run Code Online (Sandbox Code Playgroud)
当写入数据库时,Mongoose模式用于在端点处理程序级别创建给定资源的新实例。
router.post('/', validate, routeHandler(async (ctx) => {
const userObj = new User(ctx.request.body);
const user = await userObj.save();
ctx.send(201, {
success: true,
user,
});
}));
Run Code Online (Sandbox Code Playgroud)
Joi模式在验证中间件中用于验证用户输入。对于每种资源,我有3种不同的Joi模式,因为允许的输入取决于请求方法(POST,PUT,PATCH)而有所不同。
async function validate(ctx, next) {
const user = ctx.request.body;
const { method } = ctx.request;
const schema = schemas[method];
const { error } = Joi.validate(user, schema);
if (error) {
ctx.send(400, {
success: false,
error: 'Bad request',
message: error.details[0].message,
});
} else {
await next();
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道我目前使用的在Mongoose之上使用多个Joi模式的方法是否最优,因为Mongoose也具有内置的int验证。如果没有,应遵循哪些良好做法?
谢谢!
小智 5
即使您有猫鼬模式,实现验证服务也是一种常见的做法。正如您所说,在对数据执行任何登录之前,它会返回验证错误。所以,在这种情况下肯定会节省一些时间。此外,您可以使用 joi 获得更好的验证控制。但是,这在很大程度上取决于您的要求,因为它会增加您必须编写的额外代码,这些代码可以避免,而不会对最终结果产生太大影响。
归档时间: |
|
查看次数: |
452 次 |
最近记录: |