Swagger YAML无法渲染问题:ViewMedicationDto配置错误如何排查
问题根因说明
你最初的配置存在3个不符合OpenAPI规范/YAML语法的问题,都会直接导致Swagger无法正常解析渲染:
- 第一处错误:
medicationTags字段直接定义为空数组medicationTags: [],不符合OpenAPI 3.0+的规范要求,数组类型必须显式声明type: array并指定items的类型,不能用空数组占位。 - 第二处错误:示例部分语法缩进错误,你给example加了
-表示数组项,但后续的id/pui等字段和这个-平级没有缩进,会被YAML解析为多个独立的数组项,而非同一个对象的属性,直接触发解析失败。 - 第三处错误:你将
ViewMedicationDto本身定义为type: array,但对应的TS类是单个实体对象的定义,该定义不符合实际数据结构:如果需要返回该DTO的数组,应该在接口响应的schema处声明type: array,items引用#/components/schemas/ViewMedicationDto,不要把DTO本身定义为数组类型。
可正常渲染的完整配置参考
/** * @openapi * components: * schemas: * ViewMedicationDto: * type: object * properties: * _type: * type: string * id: * type: string * pui: * type: string * medicationType: * type: string * tradeName: * type: string * medicationTags: * type: array * items: * type: object * createdOn: * type: string * format: date-time * updatedOn: * type: string * format: date-time * example: * _type: ViewMedicationDto * id: 61ae82c8f95692912cc423ed * pui: test_danielcortes_821205_59909 * medicationType: Rescue * tradeName: Accolate * medicationTags: [{}, {}] * createdOn: 2021-12-06T21:38:16.359Z * updatedOn: 2021-12-06T21:38:16.359Z */ export class ViewMedicationDto implements DtoInterface { readonly _type = 'ViewMedicationDto'; readonly id: ID readonly pui: string readonly medicationType: MedicationType readonly tradeName: string readonly medicationTags?: ITag[] readonly createdOn?: Date readonly updatedOn?: Date constructor(id: ID, pui: string, medicationType: MedicationType, tradeName: string, medicationTags?: ITag[], createdOn?: Date, updatedOn?: Date) { this.id = id this.pui = pui this.medicationType = medicationType this.tradeName = tradeName this.medicationTags = medicationTags this.createdOn = createdOn this.updatedOn = updatedOn } }
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

