1

While I am having a generic class (a class taking a generic type as its input) as the type in a swagger @ApiResponse decorator, I am seeing a circular dependency issue as follows:

            throw new Error(`A circular dependency has been detected (property key: "${key}"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers ("type: () => ClassType").`);
                  ^
Error: A circular dependency has been detected (property key: "records"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers ("type: () => ClassType").
    at SchemaObjectFactory.createNotBuiltInTypeReference (nest-services\node_modules\@nestjs\swagger\dist\services\schema-object-factory.js:212:19)

Here is my controller:

  @Get()
  @ApiResponse(
      {
        status: HttpStatus.OK,
        description: something,
        type: () => ApiCollectionResponse,
        isArray: true,
      },
    ),
  )
  list(@Query() query?: ProcessedQuery): Promise<ApiCollectionResponse<Object>> {
    return this.service.list(query);
  }

My ApiCollectionResponse looks like:

export class ApiCollectionResponse<T> {
  records?: T[];
  count: number;
  next?: string;
  constructor(typeAsObject: new (Response) => T, Response: any, query: Record<string, string> = {}) {
      this.records = Response.map((item) => new typeAsObject(item)) || [];
      this.count = this.records.length;
      this.next = Response.next;
    }
}

The Service's list method looks like:

  async list(query?: ProcessedQuery): Promise<ApiCollectionResponse<Object>> {
      // Service logic
  }

The following things I have tried out while passing the type in the ApiResponse:

  1. type: Object
  2. type: () => { return new ApiCollectionResponse(Aggregate, undefined); }

None of these works.

Of course if I use some non-generic class in the type (lets say Object), it works nicely. But that's not the intention! The swagger will be incorrect for that case.

How can I overcome it?

Pradip
  • 509
  • 1
  • 5
  • 22

0 Answers0