Skip to content
This repository has been archived by the owner on Apr 15, 2020. It is now read-only.

Commit

Permalink
fix(stitching): filter unused variables from map
Browse files Browse the repository at this point in the history
  • Loading branch information
yaacovCR committed Dec 25, 2019
1 parent 8cc76d5 commit 3f0c1b3
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions src/transforms/FilterToSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,22 @@ export default class FilterToSchema implements Transform {
}

public transformRequest(originalRequest: Request): Request {
const document = filterDocumentToSchema(
this.targetSchema,
originalRequest.document,
);
return {
...originalRequest,
document,
...filterToSchema(
this.targetSchema,
originalRequest.document,
originalRequest.variables,
),
};
}
}

function filterDocumentToSchema(
function filterToSchema(
targetSchema: GraphQLSchema,
document: DocumentNode,
): DocumentNode {
variables: Record<string, any>,
): { document: DocumentNode; variables: Record<string, any> } {
const operations: Array<
OperationDefinitionNode
> = document.definitions.filter(
Expand All @@ -56,6 +57,7 @@ function filterDocumentToSchema(
def => def.kind === Kind.FRAGMENT_DEFINITION,
) as Array<FragmentDefinitionNode>;

let usedVariables: Array<string> = [];
let usedFragments: Array<string> = [];
const newOperations: Array<OperationDefinitionNode> = [];
let newFragments: Array<FragmentDefinitionNode> = [];
Expand Down Expand Up @@ -110,14 +112,15 @@ function filterDocumentToSchema(
validFragmentsWithType,
usedFragments,
);
const fullUsedVariables =
const operationOrFragmentVariables =
union(operationUsedVariables, collectedUsedVariables);
usedVariables = union(usedVariables, operationOrFragmentVariables);
newFragments = collectedNewFragments;
fragmentSet = collectedFragmentSet;

const variableDefinitions = operation.variableDefinitions.filter(
(variable: VariableDefinitionNode) =>
fullUsedVariables.indexOf(variable.variable.name.value) !== -1,
operationOrFragmentVariables.indexOf(variable.variable.name.value) !== -1,
);

newOperations.push({
Expand All @@ -130,9 +133,17 @@ function filterDocumentToSchema(
});
});

const newVariables: Record<string, any> = Object.create(null);
usedVariables.forEach(variableName => {
newVariables[variableName] = variables[variableName];
});

return {
kind: Kind.DOCUMENT,
definitions: [...newOperations, ...newFragments],
document: {
kind: Kind.DOCUMENT,
definitions: [...newOperations, ...newFragments],
},
variables: newVariables,
};
}

Expand Down

0 comments on commit 3f0c1b3

Please sign in to comment.