EventBridge对接AppSync:能否通过输入转换器序列化嵌套JSON?
解决方案:EventBridge转AppSync时嵌套JSON转AWSJSON标量
你遇到的问题是EventBridge原生输入转换器确实没有内置JSON序列化能力,没法直接把嵌套对象转成字符串格式的AWSJSON标量,但这个需求是可以实现的,有两种可靠方案:
方案1:用AppSync的VTL请求模板处理
如果你的架构是EventBridge直接触发AppSync(或者AppSync以EventBridge为数据源),可以在AppSync的请求映射模板里利用VTL的内置函数完成序列化:
在AppSync的请求模板中,使用$util.toJson()函数把传入的嵌套对象转换成符合AWSJSON要求的字符串:
{ "version": "2018-05-29", "operation": "Invoke", "payload": { "query": "mutation YourMutation($outer: AWSJSON!) { updateData(outer: $outer) { id } }", "variables": { "outer": "$util.toJson($context.event.outer)" } } }
这样不管EventBus里传递的是{"outer":{"inner":"foobar"}}这种嵌套结构,AppSync都会自动把outer字段序列化为"{\"inner\":\"foobar\"}",适配AWSJSON标量类型。
方案2:通过Lambda中间层转换
如果必须在EventBridge层面完成转换,可以加一个Lambda作为中间转发层:
- 配置EventBridge规则触发该Lambda
- 在Lambda里将嵌套对象序列化为字符串,再构造符合要求的请求发送给AppSync
示例Node.js Lambda代码:
exports.handler = async (event) => { // 序列化嵌套的outer对象为字符串 const transformedVars = { outer: JSON.stringify(event.outer) }; // 发送请求到AppSync const appsyncResponse = await fetch(process.env.APPSYNC_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': process.env.APPSYNC_API_KEY // 或其他认证方式 }, body: JSON.stringify({ query: 'mutation YourMutation($outer: AWSJSON!) { updateData(outer: $outer) { id } }', variables: transformedVars }) }); return { statusCode: appsyncResponse.status, body: await appsyncResponse.text() }; };
这两种方案都能满足你“EventBus传递原生嵌套JSON,同时适配AppSync AWSJSON标量”的需求。
内容的提问来源于stack exchange,提问作者caeus
相关产品推荐
相关产品推荐

