我正在使用 Node.js、Mongoose 和 Koa 开发 RESTful API,但在架构和输入验证方面,我对最佳实践有些困惑。
目前,我对每个资源都有 Mongoose 和 Joi 模式。 Mongoose 架构仅包含有关特定资源的基本信息。例子:
const UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
},
firstName: String,
lastName: String,
phone: String,
city: String,
state: String,
country: String,
});
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(),
}
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,
});
}));
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();
}
}
我想知道我目前在 Mongoose 之上使用多个 Joi 模式的方法是否是最佳的,考虑到 Mongoose 也有内置的验证。如果没有,可以遵循哪些良好做法?
Thanks!