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(common): add new flatten options to validation pipe #14359

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

civilcoder55
Copy link

@civilcoder55 civilcoder55 commented Jan 3, 2025

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

Currently, when the validation pipe throws an error, the error messages are always flattened into an array of strings. For example:

[
    "name must be a string",
    "number must be an integer number"
]

This behavior lacks flexibility for scenarios where the original structured error format is needed.

Also for custom exceptionFactory the errors are always returned as an array of ValidationError. For example:

[
    {
        "target": {},
        "property": "name",
        "children": [],
        "constraints": {
            "isString": "name must be a string"
        }
    },
    {
        "target": {},
        "property": "number",
        "children": [],
        "constraints": {
            "isInt": "number must be an integer number"
        }
    }
]

What is the new behavior?

This PR introduces a new two options disableFlattenErrorMessages and flatExceptionFactoryMessage in the ValidationPipe to control the formatting of error messages.

  1. disableFlattenErrorMessages
    When this option is enabled, the errors will retain their original structure instead of being flattened.

For example:

@UsePipes(
  new ValidationPipe({
    disableFlattenErrorMessages: true
  }),
)

The errors will now be returned in the ValidationError structured format:

[
    {
        "target": {},
        "property": "name",
        "children": [],
        "constraints": {
            "isString": "name must be a string"
        }
    },
    {
        "target": {},
        "property": "number",
        "children": [],
        "constraints": {
            "isInt": "number must be an integer number"
        }
    }
]
  1. flatExceptionFactoryMessage
    When this option is enabled, and exceptionFactory is provided, the errors passed to exception factory will be flattened as array of strings

For example:

@UsePipes(new ValidationPipe({ flatExceptionFactoryMessage: true, exceptionFactory: (errors: ValidationError[] | string[]) => new BadRequestException(errors) }))

The errors will now be in format:

[
    "name must be a string",
    "number must be an integer number"
]

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Motivation

The motivation behind this change stems from a specific use case with WebSocket validation. When using the validation pipe with WebSockets (WebSocket Pipes Documentation), the error messages were not flattened by default. However, when I needed to flatten them, I ended up duplicating the same flattening logic in my exception handler. so I made it configurable.

@UsePipes(new ValidationPipe({ flatExceptionFactoryMessage: true, exceptionFactory: (errors: ValidationError[] | string[]) => new WsException(errors) }))
@SubscribeMessage('events')
handleEvent(client: Client, data: unknown): WsResponse<unknown> {
  const event = 'events';
  return { event, data };
}

Docs PR: nestjs/docs.nestjs.com#3173

@coveralls
Copy link

coveralls commented Jan 3, 2025

Pull Request Test Coverage Report for Build 4a7d3c00-1b1b-46c4-bdd0-5d1cd50f2722

Details

  • 12 of 12 (100.0%) changed or added relevant lines in 1 file are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage increased (+0.008%) to 91.92%

Totals Coverage Status
Change from base Build a2f27ed3-75c7-4511-bef6-63560bd452a4: 0.008%
Covered Lines: 6826
Relevant Lines: 7426

💛 - Coveralls

@civilcoder55 civilcoder55 force-pushed the feat/validation-pipe-option branch from 63fdf67 to 7fbfa8a Compare January 3, 2025 20:14
@civilcoder55 civilcoder55 changed the title feat(common): add new option disableFlattenErrorMessages to validation pipe feat(common): add new flatten options to validation pipe Jan 3, 2025
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.

2 participants