AWS Gateway CDK中配置数组类型响应模型的实现方案
这个需求完全可以实现,核心思路是先抽离复用单个Supplier的JSON Schema定义,再基于该定义生成列表类型的响应模型,既可以保证单个/列表场景的模型复用,也能生成符合预期的Swagger文档结构。
具体实现步骤
- 抽离单个Supplier的公共Schema作为全局常量,避免重复编码,后续修改字段只需要调整这一处即可
- 基于公共Schema分别定义「单个Supplier响应模型」和「Supplier列表响应模型」
- 给列表查询接口绑定列表模型,给单个供应商查询接口绑定单个模型即可
修改后完整代码
import * as cdk from 'aws-cdk-lib'; import * as apigateway from 'aws-cdk-lib/aws-apigateway'; // 抽离公共的单个Supplier Schema,全局复用 const supplierSchema: apigateway.JsonSchema = { description: "Supplier data", title: "Supplier", properties: { code: { type: apigateway.JsonSchemaType.STRING, minLength: 4, maxLength: 6}, name: { type: apigateway.JsonSchemaType.STRING, maxLength: 81}, } }; export function CreateSupplierMethods(apigw: apigateway.Resource,restApiId: string, scope: cdk.Construct, api: apigateway.RestApi) { const suppliers = apigw.addResource('suppliers') // 单个Supplier模型,用于单个查询接口 const supplierModel = new apigateway.Model(scope, "supplier-model", { modelName: "supplier", restApi: api, contentType: 'application/json', schema: supplierSchema }) // 新增Supplier列表模型,用于列表查询接口 const supplierListModel = new apigateway.Model(scope, "supplier-list-model", { modelName: "supplierList", restApi: api, contentType: 'application/json', schema: { type: apigateway.JsonSchemaType.ARRAY, items: supplierSchema, // 直接引用公共Schema,实现复用 description: "List of Supplier objects" } }) // 列表查询接口绑定列表模型 const getSuppliers = suppliers.addMethod('GET', new apigateway.MockIntegration(), { methodResponses: [{ statusCode: "200", responseModels: { "application/json": supplierListModel, } }, { statusCode: "401", }] }) // 示例:单个供应商查询接口,绑定单个模型 const supplierById = suppliers.addResource('{id}'); supplierById.addMethod('GET', new apigateway.MockIntegration(), { methodResponses: [{ statusCode: "200", responseModels: { "application/json": supplierModel } }] }) }
按照上述代码部署后,生成的Swagger文档会自动识别列表接口响应为Supplier对象数组,单个接口响应为单个Supplier对象,完全符合预期效果。
内容的提问来源于stack exchange,提问作者Piero Alberto
相关产品推荐
相关产品推荐

