-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
QueryHelper.ts
286 lines (229 loc) · 9.76 KB
/
QueryHelper.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
import { Reference } from '../entity/Reference';
import { Utils } from './Utils';
import type {
Dictionary,
EntityKey,
EntityMetadata,
EntityProperty,
EntityValue,
FilterDef,
FilterKey,
FilterQuery,
} from '../typings';
import { ARRAY_OPERATORS, GroupOperator, ReferenceKind } from '../enums';
import type { Platform } from '../platforms';
import type { MetadataStorage } from '../metadata/MetadataStorage';
import { JsonType } from '../types/JsonType';
import { helper } from '../entity/wrap';
export class QueryHelper {
static readonly SUPPORTED_OPERATORS = ['>', '<', '<=', '>=', '!', '!='];
static processParams(params: unknown): any {
if (Reference.isReference(params)) {
params = params.unwrap();
}
if (Utils.isEntity(params)) {
if (helper(params).__meta.compositePK) {
return helper(params).__primaryKeys;
}
return helper(params).getPrimaryKey();
}
if (params === undefined) {
return null;
}
if (Array.isArray(params)) {
return (params as unknown[]).map(item => QueryHelper.processParams(item));
}
if (Utils.isPlainObject(params)) {
QueryHelper.processObjectParams(params);
}
return params;
}
static processObjectParams(params: Dictionary = {}): any {
Object.keys(params).forEach(k => {
params[k] = QueryHelper.processParams(params[k]);
});
return params;
}
static inlinePrimaryKeyObjects<T extends object>(where: Dictionary, meta: EntityMetadata<T>, metadata: MetadataStorage, key?: string): boolean {
if (Array.isArray(where)) {
where.forEach((item, i) => {
if (this.inlinePrimaryKeyObjects(item, meta, metadata, key)) {
where[i] = Utils.getPrimaryKeyValues(item, meta.primaryKeys, false);
}
});
}
if (!Utils.isPlainObject(where) || (key && meta.properties[key as EntityKey<T>]?.customType instanceof JsonType)) {
return false;
}
if (meta.primaryKeys.every(pk => pk in where) && Utils.getObjectKeysSize(where) === meta.primaryKeys.length) {
return !GroupOperator[key as keyof typeof GroupOperator] && Object.keys(where).every(k => !Utils.isPlainObject(where[k]) || Object.keys(where[k]).every(v => {
if (Utils.isOperator(v, false)) {
return false;
}
if ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(meta.properties[k as EntityKey<T>].kind)) {
return this.inlinePrimaryKeyObjects(where[k], meta.properties[k as EntityKey<T>].targetMeta!, metadata, v);
}
return true;
}));
}
Object.keys(where).forEach(k => {
const meta2 = metadata.find(meta.properties[k as EntityKey<T>]?.type) || meta;
if (this.inlinePrimaryKeyObjects(where[k], meta2, metadata, k)) {
where[k] = Utils.getPrimaryKeyValues(where[k], meta2.primaryKeys, true);
}
});
return false;
}
static processWhere<T extends object>(options: ProcessWhereOptions<T>): FilterQuery<T> {
// eslint-disable-next-line prefer-const
let { where, entityName, metadata, platform, aliased = true, convertCustomTypes = true, root = true } = options;
const meta = metadata.find<T>(entityName);
// inline PK-only objects in M:N queries, so we don't join the target entity when not needed
if (meta && root) {
QueryHelper.inlinePrimaryKeyObjects(where as Dictionary, meta, metadata);
}
where = QueryHelper.processParams(where) || {};
/* istanbul ignore next */
if (!root && Utils.isPrimaryKey<T>(where)) {
return where;
}
if (meta && Utils.isPrimaryKey(where, meta.compositePK)) {
where = { [Utils.getPrimaryKeyHash(meta.primaryKeys)]: where } as FilterQuery<T>;
}
if (Array.isArray(where) && root) {
const rootPrimaryKey = meta ? Utils.getPrimaryKeyHash(meta.primaryKeys) : entityName;
const cond = { [rootPrimaryKey]: { $in: where } } as FilterQuery<T>;
return QueryHelper.processWhere({ ...options, where: cond, root: false });
}
if (!Utils.isPlainObject(where)) {
return where;
}
return Object.keys(where).reduce((o, key) => {
let value = where![key as keyof typeof where] as unknown as FilterQuery<T>;
const prop = this.findProperty(key, options);
const keys = prop?.joinColumns?.length ?? 0;
const composite = keys > 1;
if (key in GroupOperator) {
o[key] = (value as unknown[]).map((sub: any) => QueryHelper.processWhere<T>({ ...options, where: sub, root: false }));
return o;
}
// wrap top level operators (except platform allowed operators) with PK
if (Utils.isOperator(key) && root && meta && !options.platform.isAllowedTopLevelOperator(key)) {
const rootPrimaryKey = Utils.getPrimaryKeyHash(meta.primaryKeys);
o[rootPrimaryKey] = { [key]: QueryHelper.processWhere<T>({ ...options, where: value, root: false }) };
return o;
}
if (prop?.customType && convertCustomTypes && !platform.isRaw(value)) {
value = QueryHelper.processCustomType<T>(prop, value, platform, undefined, true);
}
if (prop?.customType instanceof JsonType && Utils.isPlainObject(value) && !platform.isRaw(value) && Object.keys(value)[0] !== '$eq') {
return this.processJsonCondition<T>(o as FilterQuery<T>, value as EntityValue<T>, [prop.fieldNames[0]] as EntityKey<T>[], platform, aliased);
}
if (Array.isArray(value) && !Utils.isOperator(key) && !QueryHelper.isSupportedOperator(key) && !key.includes('?')) {
if (platform.allowsComparingTuples()) {
// comparing single composite key - use $eq instead of $in
const op = !value.every(v => Array.isArray(v)) && composite ? '$eq' : '$in';
o[key] = { [op]: value };
} else {
if (!value.every(v => Array.isArray(v)) && composite) {
o[key] = { $in: [value] };
} else {
o[key] = { $in: value };
}
}
return o;
}
if (Utils.isPlainObject(value)) {
o[key] = QueryHelper.processWhere({
...options,
where: value as FilterQuery<T>,
entityName: prop?.type ?? entityName,
root: false,
});
} else {
o[key] = value;
}
return o;
}, {} as Dictionary) as FilterQuery<T>;
}
static getActiveFilters(entityName: string, options: Dictionary<boolean | Dictionary> | string[] | boolean, filters: Dictionary<FilterDef>): FilterDef[] {
if (options === false) {
return [];
}
const opts: Dictionary<boolean | Dictionary> = {};
if (Array.isArray(options)) {
options.forEach(filter => opts[filter] = true);
} else if (Utils.isPlainObject(options)) {
Object.keys(options).forEach(filter => opts[filter] = options[filter]);
}
return Object.keys(filters)
.filter(f => QueryHelper.isFilterActive(entityName, f, filters[f], opts))
.map(f => {
filters[f].name = f;
return filters[f];
});
}
static isFilterActive(entityName: string, filterName: string, filter: FilterDef, options: Dictionary<boolean | Dictionary>): boolean {
if (filter.entity && !filter.entity.includes(entityName)) {
return false;
}
if (options[filterName] === false) {
return false;
}
return filter.default || filterName in options;
}
static processCustomType<T extends object>(prop: EntityProperty<T>, cond: FilterQuery<T>, platform: Platform, key?: string, fromQuery?: boolean): FilterQuery<T> {
if (Utils.isPlainObject(cond)) {
return Utils.keys(cond).reduce((o, k) => {
if (Utils.isOperator(k, true) || prop.referencedPKs?.includes(k)) {
o[k] = QueryHelper.processCustomType<T>(prop, cond[k] as any, platform, k, fromQuery) as any;
} else {
o[k] = cond[k];
}
return o;
}, {} as FilterQuery<T>);
}
if (Array.isArray(cond) && !(key && ARRAY_OPERATORS.includes(key))) {
return (cond as FilterQuery<T>[]).map(v => QueryHelper.processCustomType(prop, v, platform, key, fromQuery)) as unknown as FilterQuery<T>;
}
return prop.customType.convertToDatabaseValue(cond, platform, { fromQuery, key, mode: 'query' });
}
private static isSupportedOperator(key: string): boolean {
return !!QueryHelper.SUPPORTED_OPERATORS.find(op => key.includes(op));
}
private static processJsonCondition<T extends object>(o: FilterQuery<T>, value: EntityValue<T>, path: EntityKey<T>[], platform: Platform, alias: boolean) {
if (Utils.isPlainObject<T>(value) && !Object.keys(value).some(k => Utils.isOperator(k))) {
Utils.keys(value).forEach(k => {
this.processJsonCondition<T>(o, value[k] as EntityValue<T>, [...path, k as EntityKey<T>], platform, alias);
});
return o;
}
if (path.length === 1) {
o[path[0] as FilterKey<T>] = value as any;
return o;
}
const operatorObject = Utils.isPlainObject(value) && Object.keys(value).every(k => Utils.isOperator(k));
const type = operatorObject ? typeof Object.values(value)[0] : typeof value;
const k = platform.getSearchJsonPropertyKey(path, type, alias) as FilterKey<T>;
o[k] = value as any;
return o;
}
static findProperty<T>(fieldName: string, options: ProcessWhereOptions<T>): EntityProperty<T> | undefined {
const parts = fieldName.split('.');
const propName = parts.pop() as EntityKey<T>;
const alias = parts.length > 0 ? parts.join('.') : undefined;
const entityName = alias ? options.aliasMap?.[alias] : options.entityName;
const meta = entityName ? options.metadata.find<T>(entityName) : undefined;
return meta?.properties[propName];
}
}
interface ProcessWhereOptions<T> {
where: FilterQuery<T>;
entityName: string;
metadata: MetadataStorage;
platform: Platform;
aliased?: boolean;
aliasMap?: Dictionary<string>;
convertCustomTypes?: boolean;
root?: boolean;
}