Swagger 3.0 components中如何编写嵌套对象的schema配置
解决方法
你遇到的问题有两个核心原因:
passwordRules的schema属性配置和实际DTO定义不匹配,漏了minRequiredLowerCase、minRequiredSymbols两个字段- 嵌套示例的写法不符合YAML/OpenAPI规范:你在顶层example中给
passwordRules赋值空对象{},会直接覆盖子属性上定义的所有示例值,所以即便子属性加了example字段也不会生效;同时混用无逗号的JSON对象语法也会导致解析失败。
正确的完整配置如下:
/** * @openapi * components: * schemas: * VerifiedEmailAddressDto: * type: object * required: * - email * properties: * _type: * type: string * email: * type: string * description: a users email. * reset: * type: boolean * passwordRules: * type: object * required: * - minLength * - maxLength * - minRequiredUppercase * - minRequiredLowerCase * - minRequiredSymbols * properties: * minLength: * type: number * example: 8 * maxLength: * type: number * example: 25 * minRequiredUppercase: * type: number * example: 1 * minRequiredLowerCase: * type: number * example: 1 * minRequiredSymbols: * type: number * example: 0 * example: * _type: VerifiedEmailAddressDto * email: pablo+test_pab001@alunacare.com * reset: false * passwordRules: * minLength: 8 * maxLength: 25 * minRequiredUppercase: 1 * minRequiredLowerCase: 1 * minRequiredSymbols: 0 */ export class VerifiedEmailAddressDto { readonly _type = "VerifiedEmailAddressDto"; readonly email: string; readonly reset: boolean; readonly passwordRules: { minLength: number; maxLength: number; minRequiredUppercase: number; minRequiredLowerCase: number; minRequiredSymbols: number }; constructor(email: string, reset: boolean, passwordRules: { minLength: number; maxLength: number; minRequiredUppercase: number; minRequiredLowerCase: number; minRequiredSymbols: number }) { this.email = email; this.reset = reset; this.passwordRules = passwordRules; } }
另外你接口定义部分的schema配置有冗余错误,需要删掉多余的type: object($ref引用会自动继承目标schema的类型定义,同时写会导致解析冲突),修正后如下:
/** * @openapi * /api/v2/auth/check_mail: * post: * tags: [Auth] * description: This endpoint checks to see if an email is unique or is in use. * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/VerifiedEmailAddressDto' * responses: * 201: * description: Get permissions. * content: * application/json: * schema: * $ref: '#/components/schemas/VerifiedEmailAddressDto' */ this.app.post(p().api.v2.auth.check_email.$url, [ // TODO restrict number of queries by IP by period of time. authMiddleware.validateEmailQuery, credentialsController.verifyEmailAddress ]);
完成以上修改后就能生成你预期的返回结构,也可以正常在接口中引用该schema。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

