AWS CDK Api网关模型引用依赖——模型引用必须是规范的形式



当其中一个模型引用另一个模型时,我试图同时使用aws CDK添加多个模型。例:

"Gender": {
"contentType": "application/json",
"modelName": "GenderModel",
"schema": {
"type": "string",
"enum": [
"Not Specified",
"Male",
"Female",
"Non-Binary"
],
"schema": "http://json-schema.org/draft-04/schema#",
"title": "GenderModel"
}
},

"Requirements": {
"contentType": "application/json",
"modelName": "RequirementsModel",
"schema": {
"type": "object",
"properties": {
"gender": {
"ref": "https://apigateway.amazonaws.com/restapis/${Token[TOKEN.791]}/models/GenderModel"
}
},
"required": [
"gender",
],
"additionalProperties": false,
"schema": "http://json-schema.org/draft-04/schema#",
"title": "RequirementsModel"
}
},

当我使用

部署失败时Model reference must be in canonical form

从我可以看到这失败,因为GenderModel不存在。如果我首先在堆栈中添加GenderModel,然后添加RequirementsModel并再次部署,它会很好地工作,因为GenderModel是先前创建的。如果我想在同一时间创建两个模型,它将失败。我试图确保addModel调用的顺序是正确的,但似乎不起作用。

解决方案发现

似乎你必须明确地指定依赖项。

modelB.node.addDependency(modelA)

这将避免错误,并以正确的顺序添加模型

问题是https://apigateway.amazonaws.com/restapis/${Token[TOKEN.791]}/models/GenderModel,特别是${Token[TOKEN.791]}部分。当没有创建API时,在CloudFormation合成时,id是未知的,并且使用占位符值- https://docs.aws.amazon.com/cdk/latest/guide/tokens.html

您可以使用Ref内部函数通过引用

来组合模型。
const getModelRef = (api: RestApi, model: Model): string => 
Fn.join(
'',
['https://apigateway.amazonaws.com/restapis/',
api.restApiId,
'/models/',
model.modelId]);
"ModelCountry":
{
"Type" : "AWS::ApiGateway::Model",
"Properties" : {
"ContentType" : "application/json",
"Description" : "Country",
"Name" : "Country",
"RestApiId" : {"Ref": "WebApi"},
"Schema": {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "ModelCountry",
"properties": {
"Id": {"type": "number"},
"Name": {"type": "string"},
"Alpha2Code": {"type": "string"},
"Alpha3Code": {"type": "string"},
"NumericCode": {"type": "string"},
"PhoneCode": {"type": "string"}
}
}
}
},
"ModelState":
{
"Type" : "AWS::ApiGateway::Model",
"DependsOn" : "ModelCountry",
"Properties" : {
"ContentType" : "application/json",
"Description" : "State",
"Name" : "State",
"RestApiId" : {"Ref": "WebApi"},
"Schema": {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"title": "ModelState",
"properties": {
"Id": {"type": "number"},
"Name": {"type": "string"},
"Country": {"$ref": {"Fn::Join" : ["", ["https://apigateway.amazonaws.com/restapis/", {"Ref": "WebApi"}, "/models/", {"Ref": "ModelCountry"}]]}},
"Alpha2Code": {"type": "string"}
}
}
}
}

最新更新