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

Return ValidationChain inside a function. #1277

Closed
bp-adipsys opened this issue Feb 8, 2024 · 1 comment
Closed

Return ValidationChain inside a function. #1277

bp-adipsys opened this issue Feb 8, 2024 · 1 comment

Comments

@bp-adipsys
Copy link

Hello,

Sorry to bother you but i cannot find an answer for this behavior with google/stackoverflow

I've a route like :

test.post(
  '/test',
  securityMiddleware,
  testValidator,
  manageValidationErrors,
  test
);

testValidator works if it's like a contant/variable :

export const testValidator = [
  check('name')
    .notEmpty()
    .custom(async value => {
      const repository = new testRepository();
      const result = await repository.findOne({name: value});
      if (result) {
        return Promise.reject('Name already used');
      }
    }),
]

But i need to dinamically build the validator so i want to put it in a function like :

export function testValidator() {
    const validator = [
      check('name')
      .notEmpty()
      .custom(async value => {
          const repository = new testRepository();
          const result = await repository.findOne({name: value});
          if (result) {
              return Promise.reject('Name already used');
          }
      }),
    ];
    // add validator some checks dinamically

   return validator;
}

It does not work. Seems the middleware is hanging and waiting the "next function" like a classic middleware.

Do you have some hints ? Thanks !!


Environement :

  • nodeJS : 20.5.1
  • Express-validator : 7.0.1
  • ExpressJs : 4.18.2
@bp-adipsys
Copy link
Author

bp-adipsys commented Feb 8, 2024

I can't just pass a function that return the validationChain but i can validate the chain manually and trigger the next function

export function testValidator(req, res, next) {
    const validator = [
      check('name')
      .notEmpty()
      .custom(async value => {
          const repository = new testRepository();
          const result = await repository.findOne({name: value});
          if (result) {
              return Promise.reject('Name already used');
          }
      }),
    ];
    // add validator some checks dinamically

    for(const i in validator) {
      const result = await validator[i].run(req);
    }
  next();
}

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