How do I include DTO schemas that are only used using `$ref`?

In order to allow for reusage as well as keeping my DTO objects to a managable size, I have some DTOs that are only used as part of another DTO in the form of a $ref reference. This happens most frequently, when using a dictionary with DTO properties:

export class PriceSuggestionDto {
  @ApiProperty({
    type: 'object',
    additionalProperties: { $ref: getSchemaPath(PriceDto) },
  })
  conditionPrices: Record<string, PriceDto>;
}

When viewing the generated Swagger documentation, the type of the property is Record<string, string>and there is an error message at the top of the page.

Resolver error at paths./price-suggestions.get.responses.200.content.application/json.schema.items.properties.conditionPrices.properties.$ref
Could not resolve reference: Could not resolve pointer: /components/schemas/PriceDto does not exist in document

Is it possible to force NestJS to include the specified DTO into swagger’s schemas?

You can use the ApiExtraModels decorator to include DTOs that are not directly part of any requests or responses. You can add this anywhere, but it probably makes most sense above the DTO that references the $ref:

@ApiExtraModels(PriceDto)
export class PriceSuggestionDto {
  @ApiProperty({
    type: 'object',
    additionalProperties: { $ref: getSchemaPath(PriceDto) },
  })
  conditionPrices: Record<string, PriceDto>;
}

You can also add it using the extraModels property when generating the swagger document:

const document = SwaggerModule.createDocument(app, options, {
  extraModels: [PriceDto],
});

Source: https://docs.nestjs.com/openapi/types-and-parameters#extra-models

Leave a Comment