我想阻止使用已经存在的电子邮件地址进行注册。是否可以为此使用express-validator的新语法?例如:

  router.post('/register', [
    check('email').custom((value, {req}) => {
        return new Promise((resolve, reject) => {
           Users.findOne({email:req.body.email}, function(err, user){
           if(err) {
             reject(new Error('Server Error'))
           }
           if(Boolean(user)) {
             reject(new Error('E-mail already in use'))
           }
           resolve(true)
         });
    });
  })
]
....


我将如何通过用户?

最佳答案

express-validator仅了解请求对象本身,这使最终用户的复杂性降低了。
更重要的是,它仅真正了解请求的输入位置-bodycookiesheadersqueryparams

您的自定义验证程序是完全正确的。话虽如此,它可能无法测试,因为您似乎依赖于全局上下文。

为了使其可测试,我看到的2个选项是:

1.注入req.Users

这将涉及使用一些将您的商店对象设置为req的中间件:

// Validator definition
const emailValidator = (value, { req }) => {
  return req.Users.findOne({ email: value }).then(...);
}

// In production code
// Sets req.Users, req.ToDo, req.YourOtherBusinessNeed
app.use(myObjectsStore.middleware);
app.post('/users', check('email').custom(emailValidator));

// In tests
req = { Users: MockedUsersObject };
expect(emailValidator('foo@bar.com', { req })).rejects.toThrow('email exists');


2.编写一个工厂函数来返回您的验证器的实例:

这是我的首选解决方案,因为它不再涉及使用request对象。

// Validator definition
const createEmailValidator = Users => value => {
  return Users.findOne({ email: value }).then(...);
};

// In production code
app.post('/users', [
  check('email').custom(createEmailValidator(myObjectsStore.Users)),
]);

// Or in tests
expect(createEmailValidator(MockedUsersObject)('foo@bar.com')).rejects.toThrow('email exists');




希望这可以帮助!

关于node.js - 如何将参数传递给自定义的express-validator?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51411600/

10-12 01:00