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

AWS Amplify GraphQL API 如何基于数组内值过滤订阅

基于数组包含条件过滤 GraphQL 订阅的实现方法

默认的@aws_subscribe指令仅支持字段等值匹配,无法直接判断数组是否包含指定ID,你可以通过修改订阅对应的VTL请求映射模板实现该需求,具体方案如下:

方案1:自定义订阅过滤规则

第一步:定义带过滤参数的订阅字段

首先在Schema中声明订阅,传入要匹配的editor ID参数:

type Post @model {
  id: ID!
  author: ID!
  editors: [ID]
}

type Subscription {
  # 新增按editor ID过滤的订阅
  onCreatePostByEditorId(editorId: ID!): Post 
    @aws_subscribe(mutations: ["createPost"])
}

第二步:修改订阅的请求映射模板

找到onCreatePostByEditorId订阅对应的VTL请求模板,把默认的等值匹配逻辑改成数组包含判断,模板示例如下:

{
  "version": "2018-05-29",
  "payload": {
    "editorId": $util.toJson($context.arguments.editorId)
  },
  "filter": {
    "expression": "contains(#editors, :editorId)",
    "expressionNames": {
      "#editors": "editors"
    },
    "expressionValues": {
      ":editorId": $util.dynamodb.toDynamoDBJson($context.arguments.editorId)
    }
  }
}

方案2:借助Amplify @auth规则自动过滤

如果你使用的是Amplify框架,也可以通过@auth指令的多所有者配置直接实现该效果,无需手动改VTL模板,配置示例:

type Post 
  @model
  @auth(rules: [
    { allow: owner, ownerField: "editors", operations: [read] }
  ])
{
  id: ID!
  author: ID!
  editors: [ID]
}

配置完成后订阅onCreatePost时,会自动过滤出当前登录用户ID在editors数组内的变更消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:09:02