简体   繁体   English

如何将 apollo federation gateway 与中间件一起使用

[英]how to use apollo federation gateway with middleware

I'm using apollo federation + typescript to implement a graphql server with subgraphs.我正在使用 apollo federation + typescript 来实现带有子图的 graphql 服务器。 Currently I'm working on the gateway, and I want to apply middleware to it, which will perform a token exchange functionality.目前我正在研究网关,我想将中间件应用到它,这将执行令牌交换功能。 The problem is that I can't get my gateway running.问题是我无法让我的网关运行。 Here is the test code.这是测试代码。

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);
    })
  }

when I run the code I get no errors or warnings, but I cannot connect to my gateway via graphql client.当我运行代码时,我没有收到任何错误或警告,但我无法通过 graphql 客户端连接到我的网关。 What is the problem and how can It be fixed?有什么问题,如何解决? Thank you in advance.先感谢您。

If you want to share tokens between the gateway and the subgraph,如果要在网关和子图之间共享令牌,

you can do it in the following way.您可以通过以下方式进行操作。

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 文件 url

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM