Search code examples
typescripttypesswaggernestjs

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?


Solution

  • 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>> {}
    }