-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparseGql.ts
64 lines (54 loc) · 1.56 KB
/
parseGql.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function parse(ast, preDefs = {}) {
const { definitions } = ast;
const opDef = definitions[0];
const { operation, variableDefinitions, selectionSet } = opDef;
const variables = parseVariableDefinition(variableDefinitions, preDefs);
const queries = selectionSet.selections || [];
const queryObjects = queries.map((query) => {
const opName = query.name.value;
const args = query.arguments || [];
const argumentValues = parseArguments(args);
const selectionFields = parseSelection(query.selectionSet);
for (const key of Object.keys(argumentValues)) {
if (variables[key]) argumentValues[key] = variables[key];
}
return {
operationName: opName,
variables: {
...argumentValues,
},
selectedFields: selectionFields,
};
});
return {
type: operation,
queryObjects,
};
}
function parseArguments(args) {
const result = {};
for (const arg of args) {
result[arg.name.value] = arg.value.fields
? parseArguments(arg.value.fields)
: arg.value.value;
}
return result;
}
function parseVariableDefinition(variables, def) {
const values = {};
for (const variable of variables) {
const name = variable.variable.name.value;
values[name] = def[name] || undefined;
}
return values;
}
function parseSelection({ selections = [] }) {
return selections.reduce((acc: any, current: any) => {
const fieldName = current.name.value;
acc[fieldName] = current.selectionSet
? parseSelection(current.selectionSet)
: 1;
return acc;
}, {});
}
export default parse;