当其中一个模型引用另一个模型时,我尝试使用 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"}
}
}
}
}