typescript - como usar o gateway do apollo federation com middleware
Estou usando Apollo Federation + TypeScript para implementar um servidor GraphQL com subgrafos. Atualmente, estou trabalhando no gateway e quero aplicar um middleware nele, que realizará uma funcionalidade de troca de token. O problema é que não consigo fazer meu gateway funcionar. Aqui está o código de teste.
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);
})
}
quando eu executo o código, não obtenho erros ou avisos, mas não consigo me conectar ao meu gateway via cliente graphql. Qual é o problema e como pode ser corrigido? Obrigado antecipadamente.
Resposta #1
Se você quiser compartilhar tokens entre o gateway e o subgraph,
você pode fazer isso da seguinte maneira.
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 });
},
});
URL do documento
