Lambda返回数据类型不匹配:期望LIST类型错误排查
GraphQL类型不匹配问题排查与解决
我在schema.graphql中定义了查询listCourses,返回类型为[Course],同时定义了Course类型。前端通过GraphQL查询调用该接口触发Lambda,Lambda中返回的data是对象数组,但仍收到错误:"Can't resolve value (/listCourses) : type mismatch error, expected type LIST",通过AppSync测试也会出现该错误。
相关代码如下:
Schema定义
type Query { listCourses(param1: String, param2: String): [Course] } type Course { id: ID! fullname: String shortname: String idnumber: String summary: String }
前端调用代码
async getDataByCodeType() { const query = /* GraphQL */ ` query ListCourses($param1: String! $param2: String!) { listCourses(param1: $param1 param2: $param2) { id fullname shortname } }`; const variables = { param1: 'param1', param2: 'param1' }; try { const result = await API.graphql(graphqlOperation(query, variables)) console.log(result) } catch (error) { console.error('Error retrieving data:', error) } }
Lambda返回代码
const payload = { param1: para1, param2: para2 }; const apiResponse = await lambda.invoke({ FunctionName: FunctionName, InvocationType: "RequestResponse", Payload: JSON.stringify(payload), }).promise(); const responsePayload = JSON.parse(apiResponse.Payload); let data; switch (event.target) { case 'list_course': data = responsePayload.body.courses; break; default: throw new Error("Invalid event target"); } return { statusCode: 200, listCourse: data };
控制台输出的data
[ { id: 1, name: 'test', idnumber: 'eee', description: '' }, { id: 2, name: 'test2', idnumber: 'ccc', description: '' }, ]
问题原因与解决办法
- 核心问题:返回字段名不匹配
AppSync解析器要求返回的对象键名必须和Schema中定义的查询字段完全一致。你Schema里定义的查询是listCourses,但Lambda返回的是listCourse(少了末尾的s),导致AppSync无法识别返回的数组,报类型不匹配错误。
修改Lambda的返回语句:
return { statusCode: 200, listCourses: data };
额外注意:字段映射不一致
你返回的Course对象里用的是name和description,但Schema中定义的是fullname和summary,这会导致前端查询这两个字段时拿不到值。建议把Lambda返回的字段名调整为和Schema一致,比如把name改成fullname,description改成summary。确认数组类型有效性
虽然控制台显示data是数组,但要确保responsePayload.body.courses确实是数组类型,而不是字符串或嵌套对象。如果是字符串,需要先通过JSON.parse转换为数组。
内容的提问来源于stack exchange,提问作者user2450639
相关产品推荐
相关产品推荐

