- 在Apollo Server中设置Gateway的SelectionSetTransformer配置项:
const server = new ApolloServer({
gateway,
subscriptions: false,
context: ({ req }) => ({ req }),
plugins: [
{
requestDidStart() {
return {
async didResolveOperation({ operation }) {
operation.selectionSet = await gateway.transformRequest({
document: operation.query,
variables: operation.variables,
operationName: operation.operationName,
context: {}
}).document.definitions[0].selectionSet;
}
};
}
}
]
});
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
- 模拟GraphQL查询:
const { request } = require('graphql-request');
const { ApolloGateway } = require('@apollo/gateway');
const gateway = new ApolloGateway({
serviceList: [
{ name: 'accounts', url: 'http://localhost:4001' },
{ name: 'inventory', url: 'http://localhost:4002' },
{ name: 'products', url: 'http://localhost:4003' },
],
});
const query = `
query Products {
products {
id
name
image
}
}
`;
async function makeGatewayRequest() {
const { data } = await gateway.load({
query,
context: {},
});
console.log('Data received:', data);
const { request: subRequest } = data.products;
const subResponse = await request(subRequest.url, subRequest.query, subRequest.variables);
console.log('Sub response received:', subResponse);
}
makeGatewayRequest();