You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo Server中GraphQL订阅withFilter无法获取变量问题

解决Apollo Server订阅无法捕获参数的问题

你的问题出在subscribe函数的写法错误,导致请求参数无法传递到withFilter的回调里。

错误原因

你手动包装了asyncIterator,没有让Apollo Server正确传递请求参数到withFilter的第一个回调函数中,所以args、variables等参数都为空。

正确实现代码

调整subscribe的写法,直接返回withFilter的调用结果:

commentAdded : {
  subscribe: withFilter(
    // 第一个函数接收订阅请求的参数、上下文等
    (_, args, context, info) => pubsub.asyncIterator('EVENT_COMMENTADDED'),
    // 过滤函数里通过variables获取客户端传的userid
    (payload, variables) => {
      return payload.comment.userid === variables.userid;
    }
  ),
},

额外检查点

  • 确保你的GraphQL Schema中,Subscription类型的commentAdded字段已经定义了接收userid参数:
type Subscription {
  commentAdded(userid: String!): Comment!
}
  • 发布事件时,确保payload里的comment对象确实包含userid字段,否则过滤逻辑会失效。

内容的提问来源于stack exchange,提问作者jfjobidon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:42:10