NextJS调用Amplify/AppSync带过滤查询报错:Invalid AST Node
解决NextJS + AppSync带过滤listCards查询的AST Node错误
你的错误根源是graphqlOperation的参数格式错误——带过滤条件的查询需要把filter放在variables字段下,而非直接与query平级传入。
错误代码问题点
你当前的写法把filter直接作为配置项和query并列,导致graphqlOperation无法正确解析AST节点:
// 错误写法 const listCardsFilteredResponse = (await API.graphql( graphqlOperation({ query: listCards, filter: { clientID: { eq: "d9a6c7a2-45b1-48a8-b012-5908d216f86f" } }, }) ))
正确写法(两种可选)
写法一:直接传递变量作为第二个参数
这是最简洁的方式,graphqlOperation会自动把第二个参数解析为查询变量:
const listCardsFilteredResponse = await API.graphql( graphqlOperation(listCards, { filter: { clientID: { eq: "d9a6c7a2-45b1-48a8-b012-5908d216f86f" } } }) );
写法二:显式使用variables字段
如果需要明确配置查询和变量,可将filter嵌套在variables对象中:
const listCardsFilteredResponse = await API.graphql( graphqlOperation({ query: listCards, variables: { filter: { clientID: { eq: "d9a6c7a2-45b1-48a8-b012-5908d216f86f" } } } }) );
原理说明
AppSync生成的listCards查询定义中,filter是作为查询变量接收的(对应你错误提示里的$filter: ModelCardFilterInput)。前端代码必须通过variables传递过滤条件,才能和AppSync控制台的查询逻辑对齐——就像你在控制台里把filter作为listCards的参数传入一样。
内容的提问来源于stack exchange,提问作者JimmyTheCode
相关产品推荐
相关产品推荐

