Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to reuse a custom validation chain as router.use(xxxValidator) #1173

Open
convers39 opened this issue Sep 7, 2022 · 4 comments
Open

Comments

@convers39
Copy link

For example, I have a custom validator that consists of an array of validation:

const customValidator = (arg) => {
    const res = someLogic(arg)
    return res
}

const validateResult = (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      res.status(400).json({ errors: errors.array() })
    } else {
      next()
    }
  }


export const validator = [
    query('xx').exists(),
    customValidator,
    validateResult
]

Now in my routers/routeA.js file, I want to apply this validation to all routes in this namespace like this:

import { validator } from 'xx/xx'

const router = Router()
router.use(validator)


router.get('/endpointA', controller.funcA)
router.get('/endpointB', controller.funcB)
//...

Instead of this:

import { validator } from 'xx/xx'

const router = Router()

router.get('/endpointA', validator, controller.funcA)
router.get('/endpointB', validator, controller.funcB)
//...

And of cause, this will not match the signature:
image

I understand it requires a RequestHandler to work, is there any workaround to apply a validation chain to multiple routes?

@gustavohenke
Copy link
Member

Hey. Looks like a mismatch between express and express-validator. thanks for raising!

@gustavohenke
Copy link
Member

Are you also able to come up with a small, contained replication repo?
It happens for me with this TS playground link:
https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAUwB5iggzuuAzKERwDkyqG6hA3ALABQokscA3nAMYAWCrA1nAL448BYijSYAtADcAhgBtgAE2kxolWrVYQAdunjSwYOAF5EosgAoAlNRr6wAOgCu6BOY5du5wtggRCl63VbA3sAcwQYLwB6Hz8AGjZOHi9Y-2sgA

But it doesn't happen in any other environment, and I can't pinpoint the exact versions that cause the problem.

@convers39
Copy link
Author

Sorry for the late reply

I made a simple example to reproduce here:

https://codesandbox.io/s/gallant-violet-e181qx?file=/src/index.ts

@gustavohenke
Copy link
Member

Hey @convers39, I was taking a look at this, it seems all is fine?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants