routing-controllers: fix: Enum in @QueryParams and @QueryParam: Value cannot be parsed into JSON
Some code to reproduce issue:
enum LabelType {
Sent = 'Sent',
Inbox = 'Inbox'
}
class Query {
@IsEnum(LabelType)
label: LabelType;
}
@JsonController()
export class ThreadController {
@Get('/threads')
async list(
@QueryParams() query: Query
) {
return "ok";
}
@Get('/threads/one')
async list(
@QueryParam('label') label: LabelType,
) {
return "ok";
}
@Post('/threads')
async postList(
@Body() query: Query
) {
return "ok";
}
}
Issue:
Post method is working as expected, but Get fails with this error:
Http error: Given parameter label is invalid. Value ("Sent") cannot be parsed into JSON.
Possible reason:
Typescript emits “Object” for “design:type” when type is inferred original issue. In that case string enum treats as an object and routing-controllers tries to parse string.
That happens in normalizeParamValue method of ActionParameterHandler here. normalizeParamValue isn’t handles params from @Body, that’s why Post works as expected.
Workaround:
Until it fixed we can explicitly specify enum type. Not sure if that will not break anything else, but working fine for me:
export class Query {
@Reflect.metadata('design:type', { name: 'string' })
@IsEnum(LabelType)
label: LabelType;
}
For @QueryParam it’s possible to set parameter’s type:
@QueryParam('label', { type: 'string' }) label: LabelType
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 15
- Comments: 16 (3 by maintainers)
Anyone still having this issue? I’m trying with
@IsInas well and it still does not work.Issue is reproducable only with
--transpile-onlyflag forts-node. Works as expected without it or with compiled files.@pauloendoh keep it mind types are not available during runtime!
same problem I cant send something like
comment/b481d670from the front, unless wrap it with double quotes:comment/"b481d670"Im getting a the same error with union types (
string | string[]) or typeany. I must pass double quotes (?search="foo") for a single param to work. Im using koa@2.11.0, routing-controllers@0.8.0 typescript@3.8.3 Here is an example repo