Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics type response with swagger in nestjs

export class PaginatedResult<T> {

 @Expose()
 @ApiResponseProperty(type: T}) // Unfortunately, this is not working beacue its a type but used as a value
 @Transform(({ obj }) =>
  obj.data.map((data) => new obj.classConstructor(data)),
 )
 data: T[];
}

As you can see the data is of Type T which has the options Item or Tag and a few more, but swagger will always only display Item also on endpoints where I have defined the ResponseType as: {type: PaginatedResult<Tag>}

Is there any solution?

like image 418
Branchverse Avatar asked Oct 30 '25 04:10

Branchverse


1 Answers

I found a solution for this, but outside, instead of the Property itself, one could make a custom ApiResponseDecorator which takes the generic type and fills a schema with it:

(It's NestJs)

export const ApiOkResponseCustom = <GenericType extends Type<unknown>>(data: GenericType ) =>
  applyDecorators(
    ApiExtraModels(ModelWithGeneric, data),
    ApiOkResponse({
      description: `The paginated result of ${data.name}`,
      schema: {
        allOf: [
          { $ref: getSchemaPath(ModelWithGeneric) },
          {
            properties: {
              genericFieldName: {
                type: 'array',
                items: { $ref: getSchemaPath(data) },
              },},},],},}))

used like this:

@Controller('')
export class SomeController {

  @Get('/')
  ApiOkResponseCustom(GenericType)
  async get(): Promise<ModelWithGeneric<GenericType>> {}
}
like image 77
Branchverse Avatar answered Oct 31 '25 21:10

Branchverse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!