-
Notifications
You must be signed in to change notification settings - Fork 42
/
generateQuery.js
61 lines (50 loc) · 1.46 KB
/
generateQuery.js
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
const printName = name => {
return " " + name;
};
const handleNested = (fieldsPath, fieldType) => {
const fields = recursiveQuery(fieldsPath);
return fields ? ` ${fieldType} { ${fields} }` : "";
};
const _query = property => {
// Special cases (nested values)
if (property.name === "allOf") {
if (property.type.ofType) {
return handleNested(property.type.ofType.fields, "allOf");
}
return handleNested(property.type.fields, "allOf");
}
if (property.name === "oneOf") {
if (property.type.ofType) {
return handleNested(property.type.ofType.fields, "oneOf");
}
return handleNested(property.type.fields, "oneOf");
}
// Base cases
if (!property.type) {
return printName(property.name);
}
if (property.type && !property.type.fields) {
// Base case
return printName(property.name);
}
// Normal recursion
if (property.type && property.type.fields) {
return `${printName(property.name)} { ${recursiveQuery(
property.type.fields
)} }`;
}
if (property.type && property.type.typeOf && property.type.typeOf.fields) {
return `${printName(property.name)} { ${recursiveQuery(
property.type.typeOf.fields
)} }`;
}
// If we reach this point, there's a problem.
throw new Error("No cases matched.");
};
const recursiveQuery = properties => {
if (properties === null) {
return;
}
return properties.map(property => _query(property));
};
module.exports = { recursiveQuery };