AppSync嵌套管道刻意返回Null触发错误,求解决方法
如何消除DynamoDB JS管道解析器返回null时的附带错误
问题说明
定义了Parent类型,其中可选字段childId用于从DynamoDB关联查询Child类型。当childId不存在时,预期child字段返回null(Child在Schema中为非必填),实际运行时虽返回了null,但响应中附带了错误信息。
相关代码
Schema
type Parent { parentId: String! childId: String child: Child }
JS管道请求函数
export function request(ctx) { if (!ctx.source.childId){ return } // DynamoDB 查询逻辑 }
JS管道响应函数
export function response(ctx) { return ctx.result && ctx.result.items && ctx.result.items[0] ? ctx.result.items[0] : null }
错误详情
{ "path": ["queryParent", 0, "child"], "data": null, "errorType": "Code", "errorInfo": null, "locations": [{"line": 10, "column": 13, "sourceName": null}], "message": "Request function code evaluated to null. It must match the data source request configuration." }
解决方案
错误根源是当childId不存在时,请求函数直接返回undefined,不符合DynamoDB数据源的请求格式要求。需要修改请求函数,返回一个空对象替代直接return:
export function request(ctx) { if (!ctx.source.childId){ // 返回空对象,满足数据源请求配置格式 return {} } // DynamoDB 查询逻辑 }
修改后,当无childId时,请求函数返回空对象,DynamoDB不会执行查询,响应函数会因ctx.result为空返回null,同时不会触发错误信息。原响应函数的逻辑无需改动,已正确处理ctx.result为空的情况。
内容的提问来源于stack exchange,提问作者Scott Allen
相关产品推荐
相关产品推荐

