可以使用Apollo Federation
的buildService
函数来创建一个服务,然后将其提供给Apollo Gateway
。在创建服务时,可以同时加载预先联合的schema。
示例代码:
const { ApolloGateway, RemoteGraphQLDataSource } = require('@apollo/gateway');
const { buildFederatedSchema } = require('@apollo/federation');
const { buildService } = require('@apollo/federation');
const service = buildService({
name: 'products',
url: 'http://localhost:4001/graphql',
typeDefs,
resolvers,
});
const gateway = new ApolloGateway({
serviceList: [
{ name: 'accounts', url: 'http://localhost:4002/graphql' },
{ name: 'reviews', url: 'http://localhost:4003/graphql' },
service,
],
buildService({ url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
request.http.headers.set('user-id', context.userID || '');
},
});
},
});
(async () => {
const { schema, executor } = await gateway.load();
const federatedSchema = buildFederatedSchema([{ typeDefs, resolvers }]);
// Use federatedSchema to get the pre-federated schema
})();