使用CDK+TypeScript为已有AWS API Gateway添加Model报错求助
问题原因
- 用
apiGateway.RestApi.fromRestApiId()导入的是现有API Gateway的只读引用,类型为IRestApi,这个接口仅包含读取现有资源属性的方法,没有addModel这类修改/创建关联资源的方法。 - 强制类型转换
as apiGateway.RestApi只是绕过了TypeScript的类型检查,但运行时实际对象并非RestApi类的实例,所以会报addModel is not a function的错误。
解决方法
直接使用CloudFormation原生构造CfnModel来创建Model,手动关联到目标API Gateway:
import * as apiGateway from 'aws-cdk-lib/aws-apigateway'; // 无需导入RestApi实例,直接用RestApiId创建CfnModel const errorModel = new apiGateway.CfnModel(this, 'ErrorModel', { restApiId: props.restApiId, contentType: 'application/json', name: 'Error', // 对应L2构造的modelName schema: { $schema: 'http://json-schema.org/draft-04/schema#', // 对应JsonSchemaVersion.DRAFT4的URL title: 'Error', type: 'object', properties: { errorId: { type: 'string' } } } });
补充说明
- L2构造(如
RestApi)的addModel方法是为新建API Gateway设计的,用于在创建API时同步添加Model。对于跨项目导入的现有API,只能通过Cfn级别的构造来创建关联资源,因为CDK对导入的资源仅提供只读访问。 - 如果需要在多个项目中共享API Gateway的可修改能力,建议在原项目中通过CDK的
exportValue导出必要的资源信息,或者将API Gateway的定义放在一个共享的CDK库中,让多个项目依赖该库进行扩展。
内容的提问来源于stack exchange,提问作者Mostafa -T
相关产品推荐
相关产品推荐

