为了允许重用以及将 DTO 对象保持在可管理的大小,我有一些 DTO 仅以
$ref
引用的形式用作另一个 DTO 的一部分。当使用具有 DTO 属性的字典时,这种情况最常发生:
export class PriceSuggestionDto {
@ApiProperty({
type: 'object',
additionalProperties: { $ref: getSchemaPath(PriceDto) },
})
conditionPrices: Record<string, PriceDto>;
}
查看生成的Swagger文档时,属性的类型为
Record<string, string>
,并且页面顶部有错误消息。
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
是否可以强制 NestJS 将指定的 DTO 包含到 swagger 的模式中?
您可以使用
ApiExtraModels
装饰器来包含不直接属于任何请求或响应的 DTO。您可以将其添加到任何地方,但它可能在引用 $ref
: 的 DTO 之上最有意义
@ApiExtraModels(PriceDto)
export class PriceSuggestionDto {
@ApiProperty({
type: 'object',
additionalProperties: { $ref: getSchemaPath(PriceDto) },
})
conditionPrices: Record<string, PriceDto>;
}
您还可以在生成 swagger 文档时使用
extraModels
属性添加它:
const document = SwaggerModule.createDocument(app, options, {
extraModels: [PriceDto],
});
来源:https://docs.nestjs.com/openapi/types-and-parameters#extra-models