我尝试使用
AWSIntegration
cdk 类在 AWS API Gateway 和 AWS Eventbridge 之间进行直接集成。对 API 网关端点的每个请求都应向 Eventbridge 发出一个事件。
这是传入网关的 JSON 请求正文示例:
{
"id": "5c5d0e79-b808-4d85-b765-b2b45125a72c",
"subscriber": {
"id": "595be504-9c29-4584-8e76-c7651cd5202e"
},
"event": {
"header": {
"id": "fd884d88-c8fa-4084-9edc-65d34187bdde",
"occurredOn": "2023-04-18T20:51:40.170Z",
"eventType": {
"key": "my.event.type",
"name": "my.event.type"
},
"publisher": {
"id": "cc5f5916-5cf8-4032-bd81-85817a51aec0",
"key": "publisher-environment-key",
"tags": [
{
"name": "my.item.guid",
"value": "18888872-991b-4dfd-9754-19219b8b8665"
},
{
"name": "my.item.key",
"value": "special-service"
}
]
}
}
}
}
然后我想从输入中发出具有以下属性的事件:
DetailType: "my.event.type",
Source: "my.item.key",
Detail: "...", // the whole payload that came into the gateway
事件正在发出,但我正在努力使用 JSONPath 语法从输入中提取值。我相信是因为我试图与其中包含
.
字符的值进行匹配。
这是当前的
requestTemplates
属性:
requestTemplates: {
'application/json': `
#set($context.requestOverride.header.X-Amz-Target ="AWSEvents.PutEvents")
#set($context.requestOverride.header.Content-Type ="application/x-amz-json-1.1")
${JSON.stringify({
Entries: [
{
DetailType: `$input.path('$.event.header.eventType.key')`,
Source: `$input.path('$.event.header.publisher.tags[?(@.name==my.item.key)].value')`,
Detail: "$util.escapeJavaScript($input.json('$'))",
EventBusName: eventBus.eventBusArn,
},
],
})}
`
DetailType
属性设置正确,但我得到的 Source
属性为空值。我尝试过将 my.item.key
用单引号和双引号括起来,并尝试逃避句点,但没有成功。有没有办法通过匹配 name
属性来提取该值?
我真的不想通过数组索引访问,因为它可能有不同的顺序。
为遇到同样问题的人提供解答。我能够通过利用模板中的Apache VTL来解决这个问题。
通过将我需要的属性移动到 VTL 变量中,我就可以使用数组操作来获取我需要的值。
首先将值设置到VTL变量中:
#set($publisherTags=$input.path('$.event.header.publisher.tags[?(@.name==my.item.key)]')
现在数组的具体值位于 VTL 变量中,使用数组索引并获取值。在这种情况下,可以使用索引,因为在第一步中我们通过数组内对象的属性之一进行限制。
Source: `$publisherTags[0].value`