在Mongoose最佳实践的基础上使用Joi进行验证吗?

node.js KoaJS

Tony西里

2020-04-03

我正在使用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,
});

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,
  });
}));

The Joi schema is used in validation middleware to validate user input. I have 3 different Joi schemas for each resource, because the allowed input varies depending on the request method (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();
  }
}

I am wondering if my current approach of using multiple Joi schemas on top of Mongoose is optimal, considering Mongoose also has built-int validation. If not, what would be some good practices to follow?

Thanks!

第3956篇《在Mongoose最佳实践的基础上使用Joi进行验证吗?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
卡卡西 2020.04.03

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android