Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda