-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgqlStringRebuilder.js
More file actions
88 lines (78 loc) · 2.54 KB
/
gqlStringRebuilder.js
File metadata and controls
88 lines (78 loc) · 2.54 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
function getListValues(values) {
let listValues = '';
for (let i = 0; i < values.length; i += 1) {
const separators = ['', ''];
if (values[i].kind === 'StringValue') {
separators[0] = '"';
separators[1] = '"';
} else if (values[i].kind === 'ListValue') {
listValues = `${listValues}[${getListValues(values[i].values)}]`;
} else if (values[i].kind === 'Variable') {
listValues = `${listValues}$${values[i].value}`;
} else {
listValues = `${listValues}${separators[0]}${values[i].value}${separators[1]}`;
}
if (i < values.length - 1) {
listValues = `${listValues},`;
}
}
return listValues;
}
function parseSelection(selection, query) {
let tmpQuery = query;
if (selection.alias !== undefined) {
tmpQuery += `${selection.alias.value}: `;
}
tmpQuery += selection.name.value;
if (selection.arguments.length) {
tmpQuery += '(';
for (let k = 0; k < selection.arguments.length; k += 1) {
const argument = selection.arguments[k];
const separators = ['', ''];
if (argument.value.kind === 'ListValue') {
separators[0] = '[';
separators[1] = ']';
tmpQuery = `${tmpQuery}${argument.name.value}: [${getListValues(argument.value.values)}]`;
} else if (argument.value.kind === 'Variable') {
tmpQuery = `${tmpQuery}${argument.name.value}: $${argument.value.name.value}`;
} else {
if (argument.value.kind === 'StringValue') {
separators[0] = '"';
separators[1] = '"';
}
tmpQuery = `${tmpQuery}${argument.name.value}: ${separators[0]}${argument.value.value}${separators[1]}`;
}
if (k !== selection.arguments.length - 1) {
tmpQuery += ', ';
}
}
tmpQuery += ') ';
} else {
tmpQuery += ' ';
}
return tmpQuery;
}
function filterQuery(selectionSet, queryString) {
let tmpQuery = queryString;
if (!selectionSet || selectionSet.selections.length === 0) {
return tmpQuery;
}
const { selections } = selectionSet;
tmpQuery += '{ ';
for (let i = 0; i < selections.length; i += 1) {
tmpQuery = parseSelection(selections[i], tmpQuery);
tmpQuery = filterQuery(selections[i].selectionSet, tmpQuery);
if (i === selectionSet.selections.length - 1) {
tmpQuery += '} ';
}
}
return tmpQuery;
}
function rebuildQueryString(query) {
let newQuery = '';
for (let i = 0; i < query.definitions.length; i += 1) {
newQuery = `${newQuery}${filterQuery(query.definitions[i].selectionSet, newQuery)}`;
}
return newQuery;
}
module.exports = rebuildQueryString;