UNPKG

1.3 kBJavaScriptView Raw
1import { Kind, visit } from 'graphql';
2export function extractVariables(inputValue) {
3 const path = [];
4 const variablePaths = Object.create(null);
5 const keyPathVisitor = {
6 enter: (_node, key) => {
7 if (typeof key === 'number') {
8 path.push(key);
9 }
10 },
11 leave: (_node, key) => {
12 if (typeof key === 'number') {
13 path.pop();
14 }
15 },
16 };
17 const fieldPathVisitor = {
18 enter: (node) => {
19 path.push(node.name.value);
20 },
21 leave: () => {
22 path.pop();
23 },
24 };
25 const variableVisitor = {
26 enter: (node, key) => {
27 if (typeof key === 'number') {
28 variablePaths[node.name.value] = path.concat([key]);
29 }
30 else {
31 variablePaths[node.name.value] = path.slice();
32 }
33 return {
34 kind: Kind.NULL,
35 };
36 },
37 };
38 const newInputValue = visit(inputValue, {
39 [Kind.OBJECT]: keyPathVisitor,
40 [Kind.LIST]: keyPathVisitor,
41 [Kind.OBJECT_FIELD]: fieldPathVisitor,
42 [Kind.VARIABLE]: variableVisitor,
43 });
44 return {
45 inputValue: newInputValue,
46 variablePaths,
47 };
48}