0

I'm having some problems using 2 middlewares inside the same function, already tried to search for all internet and didn't find a useful solution.

validator file

module.exports = {

create: async (req, res, next) => {
    await celebrate(options.create)(req, res, next);

    return res.status(500).json({ message: 'middleware 2'});
},

}

routes file

routes.post('/user', UserValidator.Create ,UserController.create);

The celebrate lib filters some basic validations like string lenght, null values, etc. And the celebrate() function returns another function with the (req, res, next) params.

When the celebrate returns the validation error, it stills continues to execute the code, so it tries to execute the next return and I get an error because the return has already been sent.

When using separate middlewares in the routes, it works normally:

routes.post('/user', celebrate(...), middleware2 ,UserController.create);

I also tried this way but the same thing happens, but now without an error, just returning the middleware2 result.

module.exports = {

create: async (req, res, next) => {
    await celebrate(options.create)(req, res, () => {
        return res.status(500).json({ message: 'middleware 2'});
    });
},

Is there a way to fix this?

1 Answer 1

0

u should try this structure

// API
app.post('/something', Middleware.validate, Controller.create)

//Middleware
const validate = (req, res, done) => {
  const errorArray = []
  const body = req.body

  // identifier is required, Validating as String, and length range.
  if (!_.isString(body.identifier) || body.identifier.length < 2 || body.identifier.length > 10) {
    errorArray.push({
      field: 'identifier',
      error: 70000,
      message: 'Please provide only valid \'identifier\' as string, length must be between 2 and 10.'
    })
  }



  if (!_.isEmpty(errorArray)) {
    return errorArray
  }

  done()
}

module.exports = {
  validate
}


// Controller

const create = function (req, res) {
  return // your functionality
}
module.exports = {
  create
}

Sign up to request clarification or add additional context in comments.

2 Comments

Like making the celebrate lib return the error instead of doing all the job (run next), and then treat the error?
yeah first we have to deal with validation if ther z any error in validation middleware thn just return error so that user can send correct data ... if validation is done corectly then we can move to controller to perform our functionality

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.