0

So obviously there is a knowledge gap in my basics and hence can't figure this out-

const validate = validations => {
return async (req, res, next) => {
console.log('check 3')
await Promise.all(validations.map(validation => validation.run(req)));
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
    }
res.status(400).json({ errors: errors.array() });
  };
};

This is being called by

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
res.send("succ")
});

the body() function inside validate in app.post is from express-validator

Now, how is app.post calling that middleware function const validate? I don't understand how the arguments are passing.

validations is the argument list there which should receive

validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
])

right?

But how is another brace opening saying return async (req, res, next) => { the first 2 lines are where my confusion is

const validate = validations => {
return async (req, res, next) => {
kjroger94
  • 1
  • 2
  • 1
    [Functions that return a function](https://stackoverflow.com/q/7629891) | [What do multiple arrow functions mean in javascript?](https://stackoverflow.com/q/32782922) – VLAZ Oct 01 '20 at 11:18
  • `validate`, in fact, not providing validation by itself, but returns a function which will be used in `app.` call. – Vasyl Moskalov Oct 01 '20 at 11:18
  • @VLAZ Extremely helpful articles. I was able to take that function and call it the way I wanted to. Now my only doubt is, in the middleware itself, when the `validate(obj)` call is made, it is passing arguments and calling the function again. How is that second call made that returns the resolution of the final call? It's basically doing `validate(obj)(req,res,next)` - but how is that second call invoked? – kjroger94 Oct 01 '20 at 13:05
  • @VLAZ if i change that to `app.post('/api/create-user', checkValidation, async (req, res, next) => { res.send("succ") });` and in checkValidation write `var test = validate([ body('email').isEmail(), body('password').isLength({ min: 6 }) ])(req, res, next)` I am making that call in the end. So how is app.post doing that? because `app.post('/api/create-user', validate([ body('email').isEmail(), body('password').isLength({ min: 6 }) ]), async (req, res, next) => {` in the middle this would just return the inner function right? so when is that second invocation happening and how? – kjroger94 Oct 01 '20 at 13:09

0 Answers0