【问题标题】:how to use apollo federation gateway with middleware如何将 apollo federation gateway 与中间件一起使用
【发布时间】:2022-07-29 15:12:55
【问题描述】:

我正在使用 apollo federation + typescript 来实现一个带有子图的 graphql 服务器。目前我正在研究网关,我想对其应用中间件,这将执行令牌交换功能。问题是我无法让我的网关运行。这是测试代码。

async function startGateway(port: number) {
    const app = express();
    const httpServer = http.createServer(app);

    app.use(cors({
        origin: '*',
        credentials: true,
        exposedHeaders: ['token']
    }));
    app.use(jwtMiddleware)

    const gateway = new ApolloGateway({
        supergraphSdl: new IntrospectAndCompose({
            subgraphs: [
                { name: 'subgraph', url: 'http://localhost:8081'}
            ]
        })
    });
        
    const server = new ApolloServer({
        gateway,
        plugins: [ ApolloServerPluginDrainHttpServer({ httpServer })]
    });

    await server.start();

    server.applyMiddleware({ app });

    return new Promise((resolve, reject) => {
        httpServer.listen(port)
        .once('listening', resolve)
        .once('error', reject);
    })
  }

当我运行代码时,我没有收到任何错误或警告,但我无法通过 graphql 客户端连接到我的网关。有什么问题,如何解决?提前谢谢你。

【问题讨论】:

    标签: typescript apollo-server apollo-federation apollo-gateway


    【解决方案1】:

    如果要在网关和子图之间共享令牌,

    您可以通过以下方式进行。

    class AuthenticatedDataSource extends RemoteGraphQLDataSource {
      willSendRequest({ request, context }) {
        // The header set here is transferred to the subgraph.
        request.http.headers.set('x-user-id', context.userId);
      }
    }
    
    const gateway = new ApolloGateway({
      // ...other options...
      buildService({ name, url }) {
        return new AuthenticatedDataSource({ url });
      },
    });
    

    Document url

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2018-09-05
      • 2021-01-11
      • 2018-11-19
      • 2012-03-23
      • 2020-03-31
      • 2019-03-28
      • 2019-01-15
      • 2021-05-02
      相关资源
      最近更新 更多