-
Notifications
You must be signed in to change notification settings - Fork 2
/
filter.ts
445 lines (371 loc) · 12.7 KB
/
filter.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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import {
GraphQLList,
GraphQLNonNull,
GraphQLInputObjectType,
GraphQLBoolean,
} from 'graphql';
import * as _ from 'lodash';
import { ProtocolGraphQL } from './ProtocolGraphQL';
import { ProtocolGraphQLConfiguration } from './ProtocolGraphQLConfiguration';
import { isEntity, Entity } from '../engine/entity/Entity';
import {
storageDataTypeCapabilities,
storageDataTypeCapabilityType,
} from '../engine/constants';
import { isComplexDataType } from '../engine/datatype/ComplexDataType';
import { isArray, isMap } from '../engine/util';
import { isViewEntity, ViewEntity } from '../engine/entity/ViewEntity';
import { isShadowEntity } from '../engine/entity/ShadowEntity';
import { DataTypeBoolean, DataTypeString } from '../engine/datatype/dataTypes';
import { getRegisteredEntity, getRegisteredEntityAttribute } from './registry';
const AND_OPERATOR = 'AND';
const OR_OPERATOR = 'OR';
const logicalKeysMap = {
[AND_OPERATOR]: '$and',
[OR_OPERATOR]: '$or',
};
const DEEP_FILTER_OPERATOR = 'filter';
const PRE_FILTER_OPERATOR = 'pre_filter';
export const generateFilterInput = (entity, graphRegistry) => {
const protocolConfiguration = ProtocolGraphQL.getProtocolConfiguration() as ProtocolGraphQLConfiguration;
const {
typeNamePluralPascalCase: typeNamePluralListName,
} = getRegisteredEntity(entity.name);
const storageType = entity.storageType;
const filterInputTypeName = protocolConfiguration.generateFilterInputTypeName(
entity,
);
const preFilters = entity.getPreFilters();
const entityFilterType = new GraphQLInputObjectType({
name: filterInputTypeName,
description: `Filter **\`${typeNamePluralListName}\`** by various criteria`,
fields: () => {
const fields = {
[AND_OPERATOR]: {
description: `Combine **\`${filterInputTypeName}\`** by a logical **AND**`,
type: new GraphQLList(new GraphQLNonNull(entityFilterType)),
},
[OR_OPERATOR]: {
description: `Combine **\`${filterInputTypeName}\`** by a logical **OR**`,
type: new GraphQLList(new GraphQLNonNull(entityFilterType)),
},
};
_.forEach(entity.getAttributes(), (attribute) => {
let attributeType = attribute.type;
const isPrimary = attribute.primary;
if (attribute.hidden) {
return;
}
if (attribute.mutationInput) {
return;
}
const { fieldName: gqlFieldName } = getRegisteredEntityAttribute(
entity.name,
attribute.name,
);
// it's a reference
if (isEntity(attributeType)) {
const targetEntity = attributeType;
const { typeName: targetTypeName } = getRegisteredEntity(
targetEntity.name,
);
const targetRegistryType = graphRegistry.types[targetTypeName];
const targetConnectionArgs = targetRegistryType.connectionArgs;
const fieldName = `${gqlFieldName}__${DEEP_FILTER_OPERATOR}`;
fields[fieldName] = targetConnectionArgs.filter;
const primaryAttribute = targetEntity.getPrimaryAttribute();
attributeType = primaryAttribute.type;
} else if (isShadowEntity(attributeType)) {
const targetEntity = attributeType;
const primaryAttribute = targetEntity.getPrimaryAttribute();
attributeType = primaryAttribute.type;
}
const fieldType = ProtocolGraphQL.convertToProtocolDataType(
attributeType,
entity.name,
true,
);
const storageDataType = storageType.convertToStorageDataType(
attributeType,
);
if (!isComplexDataType(attributeType)) {
fields[gqlFieldName] = {
type: fieldType,
};
}
storageDataType.capabilities.map((capability) => {
const fieldName = `${gqlFieldName}__${capability}`;
const field = {} as any;
if (
storageDataTypeCapabilities[capability] ===
storageDataTypeCapabilityType.STRING
) {
// object types and list types can only accept a string as filter
field.type = ProtocolGraphQL.convertToProtocolDataType(
DataTypeString,
entity.name,
true,
);
} else if (
storageDataTypeCapabilities[capability] ===
storageDataTypeCapabilityType.VALUE
) {
field.type = fieldType;
} else if (
storageDataTypeCapabilities[capability] ===
storageDataTypeCapabilityType.LIST
) {
field.type = new GraphQLList(new GraphQLNonNull(fieldType));
} else if (
storageDataTypeCapabilities[capability] ===
storageDataTypeCapabilityType.BOOLEAN
) {
field.type = ProtocolGraphQL.convertToProtocolDataType(
DataTypeBoolean,
entity.name,
true,
);
}
fields[fieldName] = field;
});
if (isPrimary && preFilters) {
const preFilterInputTypeName = protocolConfiguration.generateFilterPreFilterInputTypeName(
entity,
);
const fieldName = `${gqlFieldName}__${PRE_FILTER_OPERATOR}`;
const preFilterFieldType = new GraphQLInputObjectType({
name: preFilterInputTypeName,
description: `Filter **\`${typeNamePluralListName}\`** by a custom pre-filter`,
fields: () => {
const preFilterFields = {};
Object.keys(preFilters).map((preFilterName) => {
const preFilter = preFilters[preFilterName];
// TODO:
// const preFilterParamsInputTypeName = protocolConfiguration.generateFilterPreFilterParamsInputTypeName(
// entity,
// preFilterName,
// );
if (preFilter.attributes) {
// TODO
} else {
preFilterFields[preFilterName] = {
type: GraphQLBoolean,
};
}
});
return preFilterFields;
},
});
fields[fieldName] = {
type: preFilterFieldType,
description: `Filter **\`${typeNamePluralListName}\`** by a custom pre-filter`,
};
}
});
return fields;
},
});
return {
type: entityFilterType,
description: 'Filter list by various criteria',
};
};
export const splitAttributeAndFilterOperator = (str) => {
let ret;
if (typeof str === 'string') {
const splitPos = str.lastIndexOf('__');
if (splitPos > 0) {
const operator = str.substr(splitPos + 2);
const attributeName = str.substring(0, splitPos);
if (operator.length > 0 && attributeName.length > 0) {
ret = {
operator,
attributeName,
};
}
} else {
ret = {
attributeName: str,
};
}
}
if (!ret) {
throw new Error(`invalid filter '${str}'`);
}
return ret;
};
const deepFilterResolver = async (entity, filter, context, path) => {
const storageType = entity.storageType;
// eslint-disable-next-line no-use-before-define,@typescript-eslint/no-use-before-define
const transformedFilter = await transformFilterLevel(
entity,
filter,
entity.getAttributes(),
context,
path,
);
const { data } = await storageType.find(
entity,
{
all: true,
skipPermissions: true,
filter: transformedFilter,
},
context,
);
const ids = data.map(({ id }) => id);
if (ids.length < 1) {
return null;
}
return ids;
};
export const transformFilterLevel = async (
entity: Entity | ViewEntity,
filters = {},
attributes: any,
context?: any,
path?: string[],
) => {
const ret = {};
const hasFilter = {};
if (path && !isArray(path, true)) {
throw new Error(
'optional path in transformFilterLevel() needs to be an array',
);
}
const errorLocation = path ? ` at '${path.join('.')}'` : '';
if (!isEntity(entity) && !isViewEntity(entity)) {
throw new Error('transformFilterLevel() expects an entity or view entity');
}
if (!isMap(filters)) {
throw new Error(
`filter${errorLocation} needs to be an object of filter criteria`,
);
}
if (!isMap(attributes, true)) {
throw new Error('transformFilterLevel() expects an attribute map');
}
const filterKeys = Object.keys(filters);
await Promise.all(
filterKeys.map(async (filter) => {
const value = filters[filter];
if (filter === AND_OPERATOR || filter === OR_OPERATOR) {
const logicalKey = logicalKeysMap[filter];
const newPath = path ? path.slice() : [];
ret[logicalKey] = await Promise.all(
value.map(async (newFilter, idx) => {
const idxPath = newPath.slice();
idxPath.push(`${filter}[${idx}]`);
return await transformFilterLevel(
entity,
newFilter,
attributes,
context,
idxPath,
);
}),
);
return;
}
const { operator, attributeName } = splitAttributeAndFilterOperator(
filter,
);
let attribute;
const attributesNames = Object.keys(attributes);
attributesNames.map((name) => {
const { fieldName: gqlFieldName } = getRegisteredEntityAttribute(
entity.name,
attributes[name].name,
);
if (attributeName === gqlFieldName) {
attribute = attributes[name];
}
});
if (!attribute) {
throw new Error(
`Unknown attribute name '${attributeName}' used in filter${errorLocation}`,
);
}
hasFilter[attributeName] = hasFilter[attributeName] || {};
if (operator) {
if (operator === DEEP_FILTER_OPERATOR) {
hasFilter[attributeName].hasDeepFilter = true;
} else {
hasFilter[attributeName].hasComplexFilter = true;
}
} else {
hasFilter[attributeName].hasExactMatchFilter = true;
}
const realAttributeName = attribute.name;
if (
hasFilter[attributeName].hasDeepFilter &&
(hasFilter[attributeName].hasComplexFilter ||
hasFilter[attributeName].hasExactMatchFilter)
) {
throw new Error(
`Cannot combine 'filter' operator with other operators on attribute '${attributeName}' used in filter${errorLocation}`,
);
}
if (
hasFilter[attributeName].hasExactMatchFilter &&
(hasFilter[attributeName].hasComplexFilter ||
hasFilter[attributeName].hasDeepFilter)
) {
throw new Error(
`Cannot combine 'exact match' operator with other operators on attribute '${attributeName}' used in filter${errorLocation}`,
);
}
if (operator) {
ret[realAttributeName] = ret[realAttributeName] || {};
if (operator === DEEP_FILTER_OPERATOR) {
const newPath = path ? path.slice() : [];
newPath.push(filter);
const targetEntity = attributes[attributeName].type;
const resolvedList = await deepFilterResolver(
targetEntity,
value,
context,
newPath,
);
if (resolvedList) {
ret[realAttributeName].$in = resolvedList;
} else {
ret[realAttributeName].$noResult = true;
}
} else if (operator === PRE_FILTER_OPERATOR) {
const preFilters = entity.getPreFilters();
const usedPreFilters = Object.keys(value).filter((preFilterName) => {
const preFilterValue = value[preFilterName];
return isMap(preFilterValue) || preFilterValue === true;
});
if (usedPreFilters.length > 1) {
throw new Error('Multiple preFilters cannot be combined');
} else if (usedPreFilters.length === 1) {
const [usedPreFilter] = usedPreFilters;
const preFilter = preFilters[usedPreFilter];
if (!preFilter) {
throw new Error(`No preFilter named '${usedPreFilter}' found`);
}
const preFilterFn = preFilter.resolve;
const preFilterAttributes = value[preFilter];
const resolvedList = await preFilterFn(
context,
preFilterAttributes,
);
if (resolvedList) {
ret[realAttributeName].$in = resolvedList;
} else {
ret[realAttributeName].$noResult = true;
}
}
} else {
const operatorKey = `$${operator}`;
ret[realAttributeName][operatorKey] = value;
}
} else {
ret[realAttributeName] = value;
}
}),
);
return ret;
};