在Mongoose的最佳实践上使用Joi进行验证是否有效? [英] Is using Joi for validation on top of Mongoose good practice?

查看:88
本文介绍了在Mongoose的最佳实践上使用Joi进行验证是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js,Mongoose和Koa开发RESTful API,而对于模式和输入验证的最佳实践我有些犹豫.

I'm developing a RESTful API with Node.js, Mongoose and Koa and I'm a bit stuck on what are the best practices when it comes to schemas and input validation.

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

Currently I have both a Mongoose and Joi schema for each resource. The Mongoose schema only includes the basic info about the specific resource. Example:

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    lowercase: true,
  },
  firstName: String,
  lastName: String,
  phone: String,
  city: String,
  state: String,
  country: String,
});

Joi模式包含有关对象的每个属性的详细信息:

The Joi schema includes details about each property of the object:

{
  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模式用于在端点处理程序级别创建给定资源的新实例.

The Mongoose schema is used to create new instances of the given resource at endpoint handler level when writing to the database.

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)而有所不同.

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

我想知道我目前使用的在Mongoose之上使用多个Joi模式的方法是否最优,因为Mongoose也具有内置的验证功能.如果没有,应该遵循哪些良好做法?

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?

谢谢!

推荐答案

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

It is a common practice to implement a validation service even if you have mongoose schema. As you stated yourself it will return an validation error before any login is executed on the data. so, it will definitely save some time in that case. Moreover, you get better validation control with joi. But, it highly depends upon your requirement also because it will increase the extra code you have to write which can be avoided without making much difference to the end result.

这篇关于在Mongoose的最佳实践上使用Joi进行验证是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆