swagger icon indicating copy to clipboard operation
swagger copied to clipboard

Automatically detect optional @Query

Open mjgp2 opened this issue 6 years ago • 31 comments

Am I right in thinking that you could look for a ? on the query function parameter to denote that it is optional, and pick this up to set the required value on the swagger document?

It would be nicer than having to add decorators like @ApiImplicitQuery({name:'offset',required:false}) to the method I think. What do you reckon?

Thanks :)

mjgp2 avatar Jan 09 '18 16:01 mjgp2

One option will be to use a class as your query parameters:

class MyParams {
  @ApiModelProperty()
  prop: number;
  @ApiModelPropertyOptional()
  optionalProp: number;
}

@Controller('MyCtrl')
class MyCtrl {
  @Get()
  async getList(@Query() params: MyParams) {
    ...
  }
}

alisherks avatar Jan 09 '18 17:01 alisherks

Sure, good idea, but I would still rather have something where the API properties can be inferred by reflection rather than more decorators as it becomes much more verbose 👍

mjgp2 avatar Jan 09 '18 18:01 mjgp2

Keep in mind that a param could also be optional if it has a default value rather than a ?. For example:

@Controller("transactions")
export class TransactionsController {

	@ApiImplicitQuery({
		name: "limit",
		description: "The maximum number of transactions to return",
		required: false,
		type: Number
	})
	@Get("recent")
	getRecentTransactions(@Query("limit", new ToIntPipe()) limit: Number = 10) {
		...
	}
}

It would be ideal if swagger could detect the default value using reflection and document that the param is optional as well as the default values.

Also, note that in this example the param type is explicitly declared as Number, but this is also not reflected in the swagger docs if we omit the @ApiImplicitQuery({type: Number}). In fact, the try it out form field will currently not accept a number without the type specified in the ApiImplicitQuery decorator.

It would be ideal if all of these things could be inferred by reflection so that you would only need to use the @ApiImplicitQuery decorator to add the description.

jaufgang avatar Apr 18 '18 12:04 jaufgang

@jaufgang + 1

cristiboariu avatar May 18 '18 21:05 cristiboariu

+1

kvgros avatar Jun 12 '18 03:06 kvgros

Reflection doesn't give us any information about optionals/default values. We'd have to use a new script that makes use of AST to properly indicate whether something is required or not.

kamilmysliwiec avatar Feb 01 '19 12:02 kamilmysliwiec

So how do we define optional param?

kunokdev avatar Feb 21 '19 12:02 kunokdev

@kunokdev, you specify an optional param by setting required: false in the @ApiImplicitQuery decorator. (see my sample code above)

jaufgang avatar Feb 21 '19 15:02 jaufgang

The plugin released in version 4.0.0 will automatically detect optional properties in your class https://docs.nestjs.com/recipes/swagger. However, it still doesn't check controller's methods signature (something to add in the future).

kamilmysliwiec avatar Dec 03 '19 10:12 kamilmysliwiec

[..]
getRecentTransactions(@Query("limit", new ToIntPipe()) limit: Number = 10) {
[..]

You mentioned the custom pipe ToIntPipe. Does this mean the Nest.js framework does not come up with a out-of-the-box solution for this trivial example (an optional query parameter)?

While it wouldn't be a big deal to write a custom pipe that doesn't throw (as opposed to ParseIntPipe), I'm inclined to think that I'm missing something here. Any thoughts, @jaufgang ?

prinzdezibel avatar Apr 23 '20 15:04 prinzdezibel

@prinzdezibel and everyone else looking for a solution — there is a documented way to chain multiple pipes where one of them can inject a default value. The DefaultValue pipe must precede ParseIntType or whatever other pipe you're using. Here's a direct link to the section that documents this: https://docs.nestjs.com/pipes#providing-defaults

But it's true that it took me a while to find it.

mareksuscak avatar Sep 23 '20 16:09 mareksuscak

Thanks @mareksuscak. Closing

nartc avatar Nov 14 '20 05:11 nartc

@nartc - that's not actually the answer to the original question, I don't think you should have closed it :)

I think as @kamilmysliwiec says, "it still doesn't check controller's methods signature (something to add in the future)."

mjgp2 avatar Nov 17 '20 12:11 mjgp2

@kamilmysliwiec does reopening means that is being worked on?

murbanowicz avatar Dec 04 '20 16:12 murbanowicz

Maybe to add OptionalPipe for Swagger?

But the best way of course to use ?

getData(@Query('limit') limit?: number)

tamtakoe avatar Feb 09 '21 17:02 tamtakoe

@tamtakoe It doesn't work for me.

jameskuizon13 avatar Feb 17 '21 06:02 jameskuizon13

@jameskuizon1315 It doesn't work. It was an idea for contributors

tamtakoe avatar Apr 05 '21 19:04 tamtakoe

I'd like to +1 that supporting using ? to indicate an optional querystring parameter would be really nice. I'm converting an application to NestJs and was pretty surprised to find out that you have to do a workaround given how easy it is to use decorators for almost all other things. I have a very straightforward endpoint which doesn't require creating a class, so I think there should be a simpler way to accomplish this. I'm about to present my application to the team and I can tell it will be awkward to explain you have to do this workaround to get an optional property. In the past I've used io-ts and they definitely support this.

Burnett2k avatar Jun 24 '21 18:06 Burnett2k

Wow, I was quite surprised and confused why all my optional query parameters were omitted from the swagger document. It's a shame that so great framework doesn't have support for such a pretty common thing.

I tried to invastigate it further. The problem is, that Reflect.getMetadata(constants.PARAMTYPES_METADATA, instance, method.name) returns object type for all union types (eg: string | undefined) and all object types are omitted later. Unfortunately, all metadata are set outside of this swagger extension (probably in core module). Who knows what all it would break then if it was fixed.

mdorda avatar Feb 16 '22 16:02 mdorda

I tried to invastigate it further. The problem is, that Reflect.getMetadata(constants.PARAMTYPES_METADATA, instance, method.name) returns object type for all union types (eg: string | undefined) and all object types are omitted later. Unfortunately, all metadata are set outside of this swagger extension (probably in core module). Who knows what all it would break then if it was fixed.

This is a TypeScript limitation. Not much we can do on the framework side.

kamilmysliwiec avatar Feb 17 '22 09:02 kamilmysliwiec

Note to anyone checking this out today, @ApiImplicitQuery is @ApiQuery in latest versions :)

JacobMuchow avatar May 16 '22 16:05 JacobMuchow

You use @ApiQuery, set required=false and add ? before : Like this: @ApiQuery({ name: 'id', required: false, type: Number }) getUserById(@Req() req: any, @Query('id') id?: number)

habogay avatar Sep 19 '22 04:09 habogay

I tried the @habogay's way but the api always return 200 without any content, how can I fix it ?

huykon avatar Jan 27 '23 02:01 huykon

is there any solution to not mark required on swagger docs, i tried myProp? not working

ermarkar avatar Jul 22 '23 06:07 ermarkar

@ermarkar it looks like only the solution above is currently working. i failed to found anything else

You use @ApiQuery, set required=false and add ? before : Like this: @ApiQuery({ name: 'id', required: false, type: Number }) getUserById(@Req() req: any, @Query('id') id?: number)

invissiblecat avatar Jul 22 '23 23:07 invissiblecat

@ApiQuery({ name: 'id', required: false, type: Number })

This seems not to work with nestjs swagger plugin .

Snippet of my controller:

@ApiQuery({ enum: AsaasPaymentStatusQuery, required: false })
  @Get('subscriptions/:id/payments')
  listSubscriptionPayments(
    @Param('id') id: string,
    @Query('status') status?: AsaasPaymentStatusQuery,
  ) {
    return this.asaasService.listSubscriptionPayments(id, status);
  }

Swagger documentation : image

Looks like the plugin won't override or recognize @ApiQuery(), if I select the optional "status" shown on the upper image, it will take no effect on my request. It works if I fill the required "status", but it is not meant to be required.

Am I doing something wrong?

brunodmn avatar Oct 19 '23 14:10 brunodmn

Is it possible to add options object to @Query() decorator?

Something along the lines of:

getAll(@Query(`someQuery`, { optional: true }) someQuery?: string)
getAllWithTransform(@Query(`someQuery`, new Pipe(...), { optional: true }) someQuery?: number)

That would reduce the amount of decorators needed, and while not perfect, at least should improve the overall experience.

EcksDy avatar Nov 29 '23 10:11 EcksDy

@brunodmn I'm not sure, but isn't the 'name' property missing for the 'ApiQuery'? Since 'ApiQuery' itself is used to attach metadata to a function to associate it with its arguments, I think the 'name' property is required. How about adding the 'name' property like this: @ApiQuery({ enum: AsaasPaymentStatusQuery, required: false, name: 'status' })

DrRoot-github avatar Nov 30 '23 02:11 DrRoot-github

@brunodmn I'm not sure, but isn't the 'name' property missing for the 'ApiQuery'? Since 'ApiQuery' itself is used to attach metadata to a function to associate it with its arguments, I think the 'name' property is required. How about adding the 'name' property like this: @ApiQuery({ enum: AsaasPaymentStatusQuery, required: false, name: 'status' })

Thank you @DrRoot-github, adding the name makes it work (override default plugin behavior). This is not a required param by the ApiQuery though.

brunodmn avatar Nov 30 '23 12:11 brunodmn

This issue is still active.

You use @ApiQuery, set required=false and add ? before : Like this: @ApiQuery({ name: 'id', required: false, type: Number }) getUserById(@Req() req: any, @Query('id') id?: number)

This workaround helped in my situation. Would be more beautiful if just using ? works.

julianpoemp avatar Feb 19 '24 16:02 julianpoemp