Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda