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

Add simple express middleware helper #1

Open
unusualbob opened this issue Feb 6, 2022 · 0 comments
Open

Add simple express middleware helper #1

unusualbob opened this issue Feb 6, 2022 · 0 comments
Labels
enhancement New feature or request helper Helper functions exposed for ease of use in common situations

Comments

@unusualbob
Copy link
Owner

A common use-case for validation is checking that a request body is valid. This module should expose a helper to make that process easy to do inline when defining an express route.

Something like:

route.post('/login', Validate.middleware({
  username: {
    type: String,
    required: true,
    minLength: 8,
    maxLength: 50
  },
  password: {
   type: String,
   required: true,
   minLength: 12
   maxLength: 128
}), (req, res) => {
   let requestBody = req.validatedBody; // Only gets here if body passed validation
});
// internal logic something like
req.validatedBody = validator;
// or if you want a POJO (maybe make this an option, or inverse of this is an option?)
req.validatedBody = validator.toObject(); 

try {
  validator.validate()
} catch (e) {
  return res.status(400).json({ 
    error: e.firstError()
  });
}
return next();

I believe it would be best to have it reject requests by default, and you could would specify an option to have it pass just the validated instance through instead.

It would also be nice if you could pass in options, maybe something to indicate what status to use for rejections, or maybe what format the error response should be in, maybe an error response formatting function?

@unusualbob unusualbob added enhancement New feature or request helper Helper functions exposed for ease of use in common situations labels Feb 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request helper Helper functions exposed for ease of use in common situations
Projects
None yet
Development

No branches or pull requests

1 participant