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

feat: Implement middleware for schema validations #306

Merged
merged 4 commits into from
Oct 14, 2021

Conversation

LautaroPetaccio
Copy link
Contributor

This PR implements a middleware to do request body validations.
Each request is validated through a request schema and, in case of errors, the response is formatted as it was done before, with the exception of the status code that now is a 400 (bad request).

@coveralls
Copy link

Pull Request Test Coverage Report for Build 1337379287

  • 12 of 12 (100.0%) changed or added relevant lines in 4 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage increased (+0.1%) to 55.28%

Totals Coverage Status
Change from base Build 1321564241: 0.1%
Covered Lines: 1323
Relevant Lines: 2205

💛 - Coveralls

@fzavalia
Copy link
Contributor

This is great. We can now remove all the validations that were handled directly by the request handler function and there was a lot repeated

const valid = validate(req.body)

if (!valid) {
next(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should't you just throw the error as it was done inside the handlers?
Example from items router

if (validate.errors) {
      throw new HTTPError('Invalid schema', validate.errors)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can do both! Express has a try-catch surrounding handlers that will execute next(error) on error, but it is also possible to use next with the error in your middleware and it will go straight to the error handle middleware.

Copy link
Contributor

@fzavalia fzavalia left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! question is just out of curiosity

@LautaroPetaccio LautaroPetaccio merged commit 66d68ed into master Oct 14, 2021
@LautaroPetaccio LautaroPetaccio deleted the feat/validate-through-middleware branch October 14, 2021 13:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants