-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbuild-query.js
More file actions
203 lines (196 loc) · 7.61 KB
/
build-query.js
File metadata and controls
203 lines (196 loc) · 7.61 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
const { gql } = require("@apollo/client")
const { getTypesMap, getLocales } = require('./api');
const {
getEntityResponse,
getEntityResponseCollection,
getCollectionTypes,
getSingleTypes,
getTypeMap,
filterExcludedTypes,
} = require('./helpers');
const buildArgs = node => {
const args = [];
// Get all data for paginated fields.
if (node?.args?.find(arg => arg.name === 'pagination')) {
args.push('pagination:{limit:1000}');
}
if (node?.args?.find(arg => arg.name === 'publicationState')) {
args.push('publicationState: $publicationState');
}
return args.length ? `(${args.join(',')})` : '';
}
const getNodeFields = (node, typesMap, n = 0, root = false) => {
const max = 16;
if (n > max) {
return null;
}
const flatten = true;
const sep = flatten ? ' ' : '\n';
const dep = i => Array.from(new Array(i), () => flatten ? '' : ' ').join('');
switch (node.__typename) {
case '__Type':
switch (node.kind) {
case 'OBJECT':
// Prevent circular propagation.
if (/Entity$/.test(node?.name)) {
return [`${dep(n)}id`];
} else if (/RelationResponseCollection$/.test(node?.name)) {
return [`${dep(n)}data { __typename id }`];
}
if (node?.fields) {
if (root) {
return node.fields.filter(filterExcludedTypes).map(child => getNodeFields(child, typesMap, n)).join(sep);
}
return node.fields.filter(filterExcludedTypes).map(child => getNodeFields(child, typesMap, n));
}
const child = typesMap?.[node?.name];
if (child) {
return getNodeFields(child, typesMap, n);
}
return null;
case 'UNION': {
const child = typesMap?.[node?.name];
if (child) {
return [`${dep(n)}__typename`, ...child.possibleTypes.map(possibleType => {
const grandchild = typesMap?.[possibleType?.name];
if (grandchild) {
// Prevent circular propagation.
if (/Entity$/.test(node?.name)) {
return [`${dep(n)}id`];
} else if (/RelationResponseCollection$/.test(node?.name)) {
return [`${dep(n)}data { __typename id }`];
}
const fields = getNodeFields(grandchild, typesMap, n + 1);
if (fields) {
return `${dep(n)}... on ${possibleType.name} {${sep}${[`${dep(n + 1)}__typename`, ...fields].join(sep)}${sep + dep(n)}}`;
}
}
})];
}
return null;
}
case 'ENUM': {
const child = typesMap?.[node?.name];
if (child) {
return [`${dep(n + 1)}__typename`, ...child.enumValues.map(({ name }) =>
`${dep(n + 1)}${name}`,
)].join(sep);
}
break;
}
default:
return null;
}
case '__Field': {
switch (node.type.kind) {
case 'SCALAR':
case 'ENUM':
return `${dep(n)}${node.name}`;
case 'NON_NULL':
return getNodeFields({ ...node, type: node.type?.ofType }, typesMap, n);
case 'OBJECT': {
const fields = getNodeFields(node.type, typesMap, n + 1);
if (fields) {
const args = buildArgs(node);
return `${dep(n)}${node.name}${args} {${sep}${[`${dep(n + 1)}__typename`, ...fields].join(sep)}${sep + dep(n)}}`;
}
break;
}
case 'LIST':
const fields = getNodeFields(node.type?.ofType, typesMap, n + 1);
const args = buildArgs(node);
if (typeof fields === 'string') {
return `${dep(n)}${node.name}${args} {${sep}${fields}${sep + dep(n)}}`;
} else if (fields?.length) {
return `${dep(n)}${node.name}${args} {${sep}${fields.join(sep)}${sep + dep(n)}}`;
}
break;
default:
return null;
}
}
}
return null;
};
const buildQueries = (operations, typesMap) => {
return operations.map(operation => {
const isCollectionType = operation?.collectionType;
const operationName = `${operation.collectionType || operation.singleType}Query`;
const publicationState = Boolean(operation.field.args.find(arg => arg.name === 'publicationState'));
const publicationStateDef = operation.query.includes('$publicationState');
const locale = Boolean(operation.field.args.find(arg => arg.name === 'locale'));
const localeDef = operation.query.includes('$locale');
const filterInputType = typesMap?.[operation.field.args.find(arg => arg.name === 'filters')?.type?.name];
const updatedAt = Boolean((filterInputType?.inputFields || []).find(input => input.name === 'updatedAt'));
const updatedAtDef = operation.query.includes('$updatedAt');
const varDef = [
isCollectionType && '$pagination: PaginationArg',
(publicationState || publicationStateDef) && '$publicationState: PublicationState',
(locale || localeDef) && '$locale: I18NLocaleCode',
(updatedAt || updatedAtDef) && '$updatedAt: DateTime',
].filter(n => Boolean(n)).join(' ').replace(/(.+)/, '($1)');
const varSet = [
isCollectionType && 'pagination: $pagination',
publicationState && 'publicationState: $publicationState',
locale && 'locale: $locale',
updatedAt && 'filters: { updatedAt: { gt: $updatedAt } }',
].filter(n => Boolean(n)).join(' ').replace(/(.+)/, '($1)');
const variables = {
...isCollectionType && { pagination: { start: 0, limit: 1000 } },
...(publicationState || publicationStateDef) && { publicationState: 'LIVE' },
...(locale || localeDef) && { locale: operation.locale },
...(updatedAt || updatedAtDef) && { updatedAt: "1990-01-01T00:00:00.000Z" },
};
const meta = isCollectionType ? ` meta { pagination { total } }` : '';
const data = `__typename data { __typename id attributes { __typename ${operation.query} } }${meta}`;
const query = gql`query ${operationName}${varDef} { ${operation.field.name}${varSet} { ${data} } }`;
const syncQuery = gql`query ${operationName}${varDef} { ${operation.field.name}${varSet} { data { id }${meta} } }`;
return {
...operation,
operationName,
variables,
query,
syncQuery,
};
});
};
const getQueryFields = (singleTypes, collectionTypeMap, typesMap, locales) => {
const Query = typesMap?.Query;
return Query.fields.reduce((acc, field) => {
const singleType = getEntityResponse(field.type.name);
const collectionType = getEntityResponseCollection(field.type.name);
if (collectionTypeMap?.[collectionType]) {
const type = typesMap?.[collectionType];
locales.forEach(locale => {
acc.push({
field,
query: getNodeFields(type, typesMap, 4, true),
collectionType,
locale,
});
});
}
if (singleTypes?.[singleType]) {
const type = typesMap?.[singleType];
locales.forEach(locale => {
acc.push({
field,
query: getNodeFields(type, typesMap, 4, true),
singleType,
locale,
});
});
}
return acc;
}, []);
}
module.exports = async pluginOptions => {
const collectionTypes = getCollectionTypes(pluginOptions);
const collectionTypeMap = getTypeMap(collectionTypes);
const singleTypes = getSingleTypes(pluginOptions);
const singleTypeMap = getTypeMap(singleTypes);
const typesMap = await getTypesMap(pluginOptions);
const locales = await getLocales(pluginOptions);
const fields = getQueryFields(singleTypeMap, collectionTypeMap, typesMap, locales);
return buildQueries(fields, typesMap);
};