是否使用Joi进行Mongoose最佳实践的验证?

问题描述 投票:7回答:1

[我正在使用Node.js,Mongoose和Koa开发RESTful API,但在模式和输入验证方面,我仍然坚持最佳做法。

目前,每种资源都有猫鼬和Joi模式。猫鼬模式仅包含有关特定资源的基本信息。示例:

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还具有内置的验证功能。如果没有,将遵循哪些良好做法?

谢谢!

node.js rest mongoose koa joi
1个回答
0
投票

即使具有猫鼬模式,实现验证服务也是一种常见做法。正如您自己所说,在对数据执行任何登录之前,它将返回验证错误。因此,在这种情况下,肯定会节省一些时间。而且,您可以通过joi获得更好的验证控制。但是,它也很大程度上取决于您的要求,因为它会增加您必须编写的额外代码,可以避免这些代码,而不会对最终结果造成太大影响。

© www.soinside.com 2019 - 2024. All rights reserved.