是的,可以这样做:
import { buildFederatedSchema } from '@apollo/federation';
import {
ApolloGateway,
LocalGraphQLDataSource,
RemoteGraphQLDataSource
} from '@apollo/gateway';
import gql from 'graphql-tag';
const localServices = {
foo: {
schema: {
typeDefs: gql`
// ...
`,
resolvers: {
// ...
}
}
},
bar: {
schema: {
typeDefs: gql`
// ...
`,
resolvers: {
// ...
}
}
}
};
const remoteServices = {
baz: {
url: 'http://baz.local/graphql'
},
qux: {
url: 'http://qux.local/graphql'
}
};
const services = {
...localServices,
...remoteServices
};
// By providing a protocol we trick ApolloGateway into thinking that this is a valid URL;
// otherwise it assumes it's a relative URL, and complains.
const DUMMY_SERVICE_URL = 'https://';
const gateway = new ApolloGateway({
// We can't use localServiceList and serviceList at the same time,
// so we pretend the local services are remote, but point the ApolloGateway
// at LocalGraphQLDataSources instead...
serviceList: Object.keys(services).map(name => ({
name,
url: services[name].url || DUMMY_SERVICE_URL
})),
buildService({ name, url }) {
if (url === DUMMY_SERVICE_URL) {
return new LocalGraphQLDataSource(
buildFederatedSchema(
services[name].schema
)
);
} else {
return new RemoteGraphQLDataSource({
url
});
}
}
});
const apolloServer = new ApolloServer({
gateway,
subscriptions: false
});