首页 > 解决方案 > Apollo 联合网关:在编写超图时包含本地模式

问题描述

在为 Apollo Federation 的网关编写超图时,您将创建一个.yaml配置文件,其中包含到子图的路由 url。例如:https ://github.com/apollographql/supergraph-demo/blob/main/subgraphs/inventory/inventory.js

//supergraph.yaml
subgraphs:
  inventory:
    routing_url: http://inventory:4000/graphql
    schema:
      file: ./subgraphs/inventory/inventory.graphql
  products:
    routing_url: http://products:4000/graphql
    schema:
      file: ./subgraphs/products/products.graphql
  users:
    routing_url: http://users:4000/graphql
    schema:
      file: ./subgraphs/users/users.graphql

在上面的示例中,他们为每个子图启动 Apollo 服务器并组成一个超图。是否可以在不启动 Apollo 服务器且仅包含本地模式的情况下编写超图?

标签: graphqlapollographql-jsapollo-federationapollo-gateway

解决方案


你可以。按照本教程:https ://www.apollographql.com/blog/backend/using-apollo-federation-with-local-schemas/

不要使用超级图和子图,而是使用 serviceList 并有条件地构建数据源。

const gateway = new ApolloGateway({
  serviceList: [
    { name: "products", url: "http://localhost:4002" },
    { name: "countries", url: "http://countries" },
  ],
  buildService: ({ url }) => {
    if (url === "http://countries") {
      return new LocalGraphQLDataSource(getCountriesSchema());
    } else {
      return new RemoteGraphQLDataSource({
        url,
      });
    }
  },
});

推荐阅读