Skip to content

Commit

Permalink
perf: optimize replaceVariables
Browse files Browse the repository at this point in the history
  • Loading branch information
yaacovCR committed Oct 2, 2024
1 parent 86a5b75 commit ed820bf
Showing 1 changed file with 51 additions and 22 deletions.
73 changes: 51 additions & 22 deletions src/utilities/replaceVariables.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import type { Maybe } from '../jsutils/Maybe.js';

import type { ConstValueNode, ValueNode } from '../language/ast.js';
import type {
ConstValueNode,
ObjectFieldNode,
ValueNode,
} from '../language/ast.js';
import { Kind } from '../language/kinds.js';
import { visit } from '../language/visitor.js';

import type { VariableValues } from '../execution/values.js';

Expand All @@ -21,9 +24,9 @@ export function replaceVariables(
variableValues?: Maybe<VariableValues>,
fragmentVariableValues?: Maybe<VariableValues>,
): ConstValueNode {
return visit(valueNode, {
Variable(node) {
const varName = node.name.value;
switch (valueNode.kind) {
case Kind.VARIABLE: {
const varName = valueNode.name.value;
const scopedVariableValues = fragmentVariableValues?.sources[varName]
? fragmentVariableValues
: variableValues;
Expand All @@ -36,23 +39,19 @@ export function replaceVariables(
if (scopedVariableSource.value === undefined) {
const defaultValue = scopedVariableSource.signature.defaultValue;
if (defaultValue !== undefined) {
return defaultValue.literal;
return defaultValue.literal as ConstValueNode;
}
}

return valueToLiteral(
scopedVariableSource.value,
scopedVariableSource.signature.type,
);
},
ObjectValue(node) {
return {
...node,
// Filter out any fields with a missing variable.
fields: node.fields.filter((field) => {
if (field.value.kind !== Kind.VARIABLE) {
return true;
}
) as ConstValueNode;
}
case Kind.OBJECT: {
const newFields: Array<ObjectFieldNode> = [];
for (const field of valueNode.fields) {
if (field.value.kind === Kind.VARIABLE) {
const scopedVariableSource =
fragmentVariableValues?.sources[field.value.name.value] ??
variableValues?.sources[field.value.name.value];
Expand All @@ -61,11 +60,41 @@ export function replaceVariables(
scopedVariableSource?.value === undefined &&
scopedVariableSource?.signature.defaultValue === undefined
) {
return false;
continue;
}
return true;
}),
};
},
}) as ConstValueNode;
}
const newFieldNodeValue = replaceVariables(
field.value,
variableValues,
fragmentVariableValues,
);
newFields.push({
...field,
value: newFieldNodeValue,
});
}
return {
...valueNode,
fields: newFields,
} as ConstValueNode;
}
case Kind.LIST: {
const newValues: Array<ValueNode> = [];
for (const value of valueNode.values) {
const newItemNodeValue = replaceVariables(
value,
variableValues,
fragmentVariableValues,
);
newValues.push(newItemNodeValue);
}
return {
...valueNode,
values: newValues,
} as ConstValueNode;
}
default: {
return valueNode;
}
}
}

0 comments on commit ed820bf

Please sign in to comment.