how to use apollo federation gateway with middleware

982 views Asked by At

I'm using apollo federation + typescript to implement a graphql server with subgraphs. 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. What is the problem and how can It be fixed? Thank you in advance.

1

There are 1 answers

0
fuzes On

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