graphql - 是否可以有部分联合网关?

标签 graphql apollo apollo-server federation apollo-federation

我想联合服务,但为了简单起见,让联合网关也拥有自己的模式和逻辑,可以代理 REST API 端点。现在看起来我需要分别拥有联合网关服务、联合 graphql 服务和其余 <->graphql 桥接服务。无论如何,在我们的例子中,rest-graphql 网关至少暂时可以位于联邦网关中,以避免不必要的引导和维护。

看起来阿波罗联邦网关有 localServiceList这似乎正是为了这个目的。一个示例配置:

const gateway = new ApolloGateway({
    serviceList: [
        { name: "some-service", url: "http://localhost:40001/graph" }
    ],
    localServiceList: [
        { name: "rest-bridge", typeDefs }
    ]
});

但它并没有解决问题:如果有 localServiceList,它会跳过 serviceList。

所以问题是 :这是否可以在 Apollo Federation 网关中也持有自己的架构和逻辑?

最佳答案

是的,可以这样做:

import { buildFederatedSchema } from '@apollo/federation';
import {
  ApolloGateway,
  LocalGraphQLDataSource,
  RemoteGraphQLDataSource
} from '@apollo/gateway';
import gql from 'graphql-tag';

const localServices = {
  foo: {
    schema: {
      typeDefs: gql`
        // ...
      `,
      resolvers: {
        // ...
      }
    }
  },
  bar: {
    schema: {
      typeDefs: gql`
        // ...
      `,
      resolvers: {
        // ...
      }
    }
  }
};

const remoteServices = {
  baz: {
    url: 'http://baz.local/graphql'
  },
  qux: {
    url: 'http://qux.local/graphql'
  }
};

const services = {
  ...localServices,
  ...remoteServices
};

// By providing a protocol we trick ApolloGateway into thinking that this is a valid URL;
// otherwise it assumes it's a relative URL, and complains.
const DUMMY_SERVICE_URL = 'https://';

const gateway = new ApolloGateway({
  // We can't use localServiceList and serviceList at the same time,
  // so we pretend the local services are remote, but point the ApolloGateway
  // at LocalGraphQLDataSources instead...
  serviceList: Object.keys(services).map(name => ({
    name,
    url: services[name].url || DUMMY_SERVICE_URL
  })),
  buildService({ name, url }) {
    if (url === DUMMY_SERVICE_URL) {
      return new LocalGraphQLDataSource(
        buildFederatedSchema(
          services[name].schema
        )
      );
    } else {
      return new RemoteGraphQLDataSource({
        url
      });
    }
  }
});

const apolloServer = new ApolloServer({
  gateway,
  subscriptions: false
});

关于graphql - 是否可以有部分联合网关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304658/

相关文章:

typescript - @graphql-codegen 创建的 `Exact<T>` 类型的用途是什么?

types - 在 GraphQL 类型定义中创建条件属性

javascript - useMutation 返回的突变函数不传递变量

javascript - 使用 Dataloader 处理 GraphQL 字段参数?

graphql - 如何将图像从 TinyMCE 上传到 Apollo GraphQL 服务器?

javascript - 可以组合 apollo 查询(在 nuxt 内?)

graphql - 如何构建我的 graphql 模式以允许检索可能的下拉值?

Graphql + 中继 graphql-relay-js 依赖

GraphQL 查询 ID 以外的其他内容

node.js - 为什么在部署我的代码时会出现可选链接语法错误,但如果它们使用相同的 Node 版本,则不会出现在本地?