Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
How does express-validator prevent this function call from happening?

This is straight out of the express-validator documentation. I noticed that when these functions are passed as middleware, they include arguments and parenthesis, in which case they should be called at runtime right?

// ...rest of the initial code omitted for simplicity.
const { body, validationResult } = require('express-validator');

app.post(
  '/user',
  // username must be an email
  body('username').isEmail(),
  // password must be at least 5 chars long
  body('password').isLength({ min: 5 }),
  (req, res) => {
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    User.create({
      username: req.body.username,
      password: req.body.password,
    }).then(user => res.json(user));
  },
);

I jumped into the source code to try and figure out how they are preventing the function calls, but it is a little over my head. The reason I wanted to learn about this was I was interested in creating a middleware that worked in a similar fashion, where arguments could be passed without actually calling the function at runtime.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'm not going to reverse engineer some specific code, but will explain how to achieve this in general.

See the documentation for middleware for reference.

An endpoint is a function that takes two arguments. The request and the response. They are typically named req and res.

Middleware takes three arguments. The third is next which is called to pass control to the next function.

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

Now, middleware doesn't have to pass control to the next function. It can just respond.

const middleware = (req, res, next) => {
    if (typeof req.body?.username === 'undefined') {
        // No username was provided
        res.send("Error: No username was provided");
    } else {
        next();
    }
}

Now you might want this to be reusable for arguments other than username, so you can write a factory function which returns the middleware function.

const createMiddleware = (propertyName) => {

    const middleware = (req, res, next) => {
        if (typeof req.body?.[propertyName] === 'undefined') {
            // No value was provided for the propertyName
            res.send(`Error: No ${propertyName} was provided`);
        } else {
            next();
        }
    }

    return middleware;

}

And then use it:

app.use( createMiddleware('username') );
app.use( createMiddleware('password') );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!