Skip to content

Commit

Permalink
Merge pull request #2840 from hannesj/deduplicate-variable-definitions
Browse files Browse the repository at this point in the history
Deduplicate variable definitions for subqueries
  • Loading branch information
James Baxley authored Jun 13, 2019
2 parents 36cb4ff + a6723c3 commit 880821e
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 4 deletions.
77 changes: 77 additions & 0 deletions packages/apollo-gateway/src/__tests__/executeQueryPlan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,83 @@ describe('executeQueryPlan', () => {
`);
});

it('should not duplicate variable definitions', async () => {
const query = gql`
query Test($first: Int!) {
first: topReviews(first: $first) {
body
author {
name
}
}
second: topReviews(first: $first) {
body
author {
name
}
}
}
`;

const operationContext = buildOperationContext(schema, query);
const queryPlan = buildQueryPlan(operationContext);

const requestContext = buildRequestContext();
requestContext.request.variables = { first: 3 };

const response = await executeQueryPlan(
queryPlan,
serviceMap,
requestContext,
operationContext,
);

expect(response.data).toMatchInlineSnapshot(`
Object {
"first": Array [
Object {
"author": Object {
"name": "Ada Lovelace",
},
"body": "Love it!",
},
Object {
"author": Object {
"name": "Ada Lovelace",
},
"body": "Too expensive.",
},
Object {
"author": Object {
"name": "Alan Turing",
},
"body": "Could be better.",
},
],
"second": Array [
Object {
"author": Object {
"name": "Ada Lovelace",
},
"body": "Love it!",
},
Object {
"author": Object {
"name": "Ada Lovelace",
},
"body": "Too expensive.",
},
Object {
"author": Object {
"name": "Alan Turing",
},
"body": "Could be better.",
},
],
}
`);
});

it('can execute an introspection query', async () => {
const operationContext = buildOperationContext(
schema,
Expand Down
21 changes: 17 additions & 4 deletions packages/apollo-gateway/src/executeQueryPlan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,14 +339,27 @@ function mapFetchNodeToVariableDefinitions(
node: FetchNode,
): VariableDefinitionNode[] {
const variableUsage = node.variableUsages;
return variableUsage
? variableUsage.map(({ node, type }) => ({
if (!variableUsage) {
return [];
}

const variableMap = variableUsage.reduce((map, { node, type }) => {
const key = `${node.name.value}_${type.toString()}`;

if (!map.has(key)) {
map.set(key, {
kind: Kind.VARIABLE_DEFINITION,
variable: node,
type: astFromType(type),
}))
: [];
});
}

return map;
}, new Map<string, VariableDefinitionNode>());

return Array.from(variableMap.values());
}

function operationForRootFetch(
fetch: FetchNode,
operation: OperationTypeNode = 'query',
Expand Down

0 comments on commit 880821e

Please sign in to comment.