I am using Apollo gateway to build a graphql federation service. Below is the demo code:
const gateway = new ApolloGateway({
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{ name: 'products', url: 'https://products-service.dev/graphql' },
{ name: 'reviews', url: 'https://reviews-service.dev/graphql' },
],
introspectionHeaders: {
Authorization: 'Bearer abc123',
},
}),
});
As you can see there are 2 subgraphs products
and reviews
, and there is also a introspectionHeaders
which gives authorization. My questions is:
you can use use buildService
...something this:
const authMap = {
'products': 'abc',
'reviews': 'xyz'
}
const gateway = new ApolloGateway({
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{ name: 'products', url: 'https://products-service.dev/graphql' },
{ name: 'reviews', url: 'https://reviews-service.dev/graphql' },
]
}),
buildService (item: ServiceEndpointDefinition) {
const { url, name } = item
return new RemoteGraphQLDataSource({
url,
willSendRequest (options: any) {
const { request } = options
request.http.headers.set('Authorization' `Bearer ${authMap[name]}`)
}
})
}
})