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

如何在Apollo Federation 2中为字段传递输入参数?

在Apollo GraphQL Federation 2中传递关联字段参数实现过滤

当然可以实现你的需求!在Federation 2架构下,要把searchTerm参数从Product子图传递到Category子图,需要调整解析器的实现,让网关能正确把参数传递给目标子图的实体解析逻辑。下面是具体的实现步骤:

1. 子图1的Schema修改(你已完成这一步)

首先在Product类型的category字段上添加searchTerm参数,作为触发过滤的入口:

type Product @key(fields: "id") {
    id: ID!
    title: String!
    description: String
    price: Int!
    category(searchTerm: String): [Category!]
  }

type Category @key(fields: "id") {
    id: ID!
  }

type Query {
    product(id: ID!): Product
  }

2. 子图1解析器:传递参数到Category子图

在子图1的Product解析器中,处理category字段时,除了返回关联Category的实体引用(包含__typename和id),还要把searchTerm参数附加到引用对象中。网关会自动把这些附加参数传递给Category子图的实体解析器:

以JavaScript为例:

const resolvers = {
  Product: {
    category: async (parent, { searchTerm }, { dataSources }) => {
      // 从子图1数据源获取当前产品关联的所有Category ID
      const categoryIds = await dataSources.productDB.getCategoryIds(parent.id);
      
      // 返回Category实体引用列表,并携带searchTerm参数
      return categoryIds.map(id => ({
        __typename: "Category",
        id,
        searchTerm // 该参数会被网关自动传递到子图2
      }));
    }
  }
};

3. 子图2解析器:接收参数并过滤

在子图2的Category实体解析器(__resolveReference)中,接收从子图1传递过来的searchTerm参数,然后根据参数过滤返回的Category数据:

const resolvers = {
  Category: {
    __resolveReference: async (reference, { dataSources }) => {
      const { id, searchTerm } = reference;
      
      // 从子图2数据源获取Category详情
      const category = await dataSources.categoryDB.getCategoryById(id);
      
      // 根据searchTerm过滤:如果有搜索词且不匹配,则返回null(网关会自动过滤掉null项)
      if (searchTerm && category.title.toLowerCase() !== searchTerm.toLowerCase()) {
        return null;
      }
      
      return category;
    }
  }
};

4. 验证查询

现在执行你想要的查询:

query Product($productId: ID!) {
  product(id: $productId) {
    id
    title
    category(searchTerm: "sport") {
      id
      title
    }
  }
}

网关会自动处理参数传递,最终返回仅符合searchTerm条件的Category列表。

关键注意点

  • 遵循联邦职责划分:子图1只负责管理Product与Category的关联关系,Category的属性(如title)和过滤逻辑由子图2处理,保持了微服务的独立性。
  • 实体引用传递参数:Federation 2支持在实体引用中附加自定义参数,网关会自动将这些参数传递给目标子图的__resolveReference方法,无需额外的Schema声明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:35:28