Repository navigation
fix(common): Support numeric string values in ParseEnumPipe - #17668
kamilmysliwiec merged 3 commits into
Conversation
| if (this.isNumeric(value)) { | ||
| const enumValues = this.getEnumValues(); | ||
| if (!enumValues.includes(value) && enumValues.includes(Number(value))) { | ||
| return Number(value) as T; | ||
| } | ||
| } | ||
| return value as T; |
There was a problem hiding this comment.
This returns Number(value) rather than the enum member that matched, and the isNumeric regex is looser than an enum lookup should be. Concretely, with enum Status { Active = 0, Inactive = 1 }:
'01','00','1.0','0.0'are accepted and mapped to1/0'-0'is accepted and the pipe returns-0, notStatus.Active(Object.is(-0, 0) === false)
It also walks Object.keys(enumType) a second time per call, right after isEnum already did.
I'd rather match a numeric member only by its exact string form (String(enumValue) === value) and return the member itself. Together with the helper suggested below on isEnum:
| if (this.isNumeric(value)) { | |
| const enumValues = this.getEnumValues(); | |
| if (!enumValues.includes(value) && enumValues.includes(Number(value))) { | |
| return Number(value) as T; | |
| } | |
| } | |
| return value as T; | |
| return (this.toEnumValue(value) ?? value) as T; |
(?? value keeps the current behavior for subclasses that override isEnum to accept something the default lookup doesn't know about.)
| protected isEnum(value: unknown): boolean { | ||
| const enumValues = Object.keys(this.enumType as object) | ||
| const enumValues = this.getEnumValues(); | ||
| if (enumValues.includes(value)) { | ||
| return true; | ||
| } | ||
| if (this.isNumeric(value)) { | ||
| return enumValues.includes(Number(value)); | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| protected isNumeric(value: unknown): boolean { | ||
| return ( | ||
| ['string', 'number'].includes(typeof value) && | ||
| /^-?\d+(\.\d+)?$/.test(String(value)) && | ||
| isFinite(value as any) | ||
| ); | ||
| } |
There was a problem hiding this comment.
Suggestion to go with the comment above: a single lookup that handles both exact matches and the string form of numeric members, so we don't need isNumeric (which is a near copy of ParseIntPipe.isNumeric with (\.\d+)? added) and the regex / isFinite / Number() dance:
| protected isEnum(value: unknown): boolean { | |
| const enumValues = Object.keys(this.enumType as object) | |
| const enumValues = this.getEnumValues(); | |
| if (enumValues.includes(value)) { | |
| return true; | |
| } | |
| if (this.isNumeric(value)) { | |
| return enumValues.includes(Number(value)); | |
| } | |
| return false; | |
| } | |
| protected isNumeric(value: unknown): boolean { | |
| return ( | |
| ['string', 'number'].includes(typeof value) && | |
| /^-?\d+(\.\d+)?$/.test(String(value)) && | |
| isFinite(value as any) | |
| ); | |
| } | |
| protected isEnum(value: unknown): boolean { | |
| return this.toEnumValue(value) !== undefined; | |
| } | |
| /** | |
| * Returns the enum member that `value` refers to, or `undefined` if there is none. | |
| * Numeric members also match their string representation (e.g. `'1'` for `1`), | |
| * since HTTP route and query params always arrive as strings. | |
| */ | |
| protected toEnumValue(value: unknown): string | number | undefined { | |
| return this.getEnumValues().find( | |
| enumValue => | |
| enumValue === value || | |
| (typeof enumValue === 'number' && | |
| typeof value === 'string' && | |
| String(enumValue) === value), | |
| ); | |
| } |
I ran this variant locally against the spec in this PR plus a set of edge cases: all of the existing tests still pass, '0' / '1' / '-5' / '100' / '0.5' (for a float-valued member) resolve to the member, string enums with digit values are untouched, and '01', '1.0', '-0', '+1', ' 1', '1e0' are rejected.
Note that isNumeric is protected, so keeping it means committing to it as an extension point (see #9496). If you'd rather keep the regex approach, please at least make it private and drop the (\.\d+)? part unless float-valued enums get a test.
| ); | ||
| } | ||
|
|
||
| protected getEnumValues(): any[] { |
There was a problem hiding this comment.
nit: this can be typed as (string | number)[], which is what enum members can be at runtime. Exposing it as a protected extension point seems fine to me.
| it('should return numeric enum value when the numeric value is passed as a string', async () => { | ||
| expect( | ||
| await numericTarget.transform('0' as any, {} as ArgumentMetadata), | ||
| ).toBe(Status.Active); | ||
| expect( | ||
| await numericTarget.transform('1' as any, {} as ArgumentMetadata), | ||
| ).toBe(Status.Inactive); | ||
| }); |
There was a problem hiding this comment.
Please also pin down the edge cases that the coercion decides on, whatever we settle on (my preference is that these are all rejected):
'01','1.0'and'-0'for theStatusenum- a mixed enum (
enum Mixed { A = 'a', One = 1 }) with'a','1'and1
And, since the regex intentionally allows decimals, a float-valued enum (e.g. enum Ratio { Half = 0.5 }) with '0.5'. Otherwise that branch of the regex is untested.
| it('should throw when an invalid numeric string is passed', async () => { | ||
| await expect( | ||
| numericTarget.transform('2' as any, {} as ArgumentMetadata), | ||
| ).rejects.toThrow(HttpException); | ||
| }); |
There was a problem hiding this comment.
HttpException is the base class of every built-in HTTP exception, so this would also pass if the pipe started throwing, say, a 500. Assert the concrete one (BadRequestException, and ideally the message) here and in the test below.
|
Thanks for the PR! A few things before the inline notes. Context / prior art
Review Requesting changes for the points below. The behavior for the happy path (
Possible follow-ups (not for this PR)
CI: the only red job is |
|
Thanks for the thorough review and suggestions @micalevisk ! |
transform() calls isEnum() and toEnumValue(), each of which rebuilt the enum value list via Object.keys().filter().map() on every request. The enum object is fixed at construction, so compute the list lazily once and reuse it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
When using
ParseEnumPipewith numeric TypeScript enums on HTTP route parameters (such as@Query()or@Param()), values are received as strings (e.g.'0'). BecauseParseEnumPipe.isEnum()uses strict equality checking against numeric enum values ([0, 1].includes('0')), it throws a400 Bad Request: "Validation failed (enum string is expected)".Issue Number: Fixes #17638
What is the new behavior?
ParseEnumPipe.isEnum()now supports numeric string values when the underlying enum values are numeric.ParseEnumPipe.transform()coerces numeric string values to numbers (Number(value)), ensuring the returned value matches the TypeScript numeric enum type instead of remaining a raw string.enum Digit { Zero = '0' }) preserve their string type and are not coerced.Does this PR introduce a breaking change?
Other information
packages/common/test/pipespassed.oxlintand formatted withprettier.