Skip to content
Advertisement

@nestjs/swagger: How to add schema without @ApiOkResponse decorator?

I have two DTOs. UsersDTO and UserDTO. UsersDTO are showing in swagger, because I have an endpoint to get users list, and for that endpoint I have

  @ApiOkResponse({
    status: HttpStatus.OK,
    type: UsersDTO,
  })

In UsersDTO I’m using UserDTO using $ref. UsersDTO looks like

export class UsersDTO {
  @ApiProperty({
    type: 'array',
    items: { $ref: getSchemaPath(UserDTO) },
  })
  @IsArray()
  readonly items: UserDTO[];

  @ApiProperty({
    type: 'object',
    properties: {
      totalItems: {
        type: 'number',
        example: 100,
      },
      itemCount: {
        type: 'number',
        example: 10,
      },
      itemsPerPage: {
        type: 'number',
        example: 10,
      },
      totalPages: {
        type: 'number',
        example: 10,
      },
      currentPage: {
        type: 'number',
        example: 2,
      },
    },
  })
  @IsObject()
  readonly meta: IMeta;
}

But it doesn’t work in swagger. Swagger show [string] as a value for the items.

Is there any way to make it work?

Advertisement

Answer

Looks like you dont have another endpoint that is using UserDTO in @ ApiOkResponse, like

@ApiOkResponse({
    status: HttpStatus.OK,
    type: UserDTO,
  })

It means that the Swagger cant make references between the Schemas.

If you add another endpoint, for example, to get a single user, and use provided @ApiOkResponse, it will work.

But, if you don’t need that endpoint, you also can provide DTO Schemas to Swagger on the setup stage in the following way

    const document = SwaggerModule.createDocument(
      app,
      new DocumentBuilder()
        .setTitle('API')
        .setDescription('API')
        .setVersion('1.0')
        .addBearerAuth()
        .build(),
      { extraModels: [UserDTO] },
    );

    SwaggerModule.setup(swaggerPath, app, document);

You can use it to add the Schemas that are not used in the endpoints directly using @ApiOkResponse decorator. extraModels is an aray with needed Schemas

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement