-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
Utils.ts
627 lines (501 loc) · 18.3 KB
/
Utils.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import fastEqual from 'fast-deep-equal';
import clone from 'clone';
import globby, { GlobbyOptions } from 'globby';
import { isAbsolute, normalize, relative } from 'path';
import { pathExists } from 'fs-extra';
import { createHash } from 'crypto';
// @ts-ignore
import { parse } from 'acorn-loose';
// @ts-ignore
import { simple as walk } from 'acorn-walk';
import { MetadataStorage } from '../metadata';
import { AnyEntity, Dictionary, EntityData, EntityMetadata, EntityProperty, Primary } from '../typings';
import { ArrayCollection, Collection, Reference, ReferenceType, wrap } from '../entity';
import { Platform } from '../platforms';
import { GroupOperator, QueryOperator } from '../enums';
export class Utils {
/**
* Checks if the argument is not undefined
*/
static isDefined<T = Record<string, unknown>>(data: any, considerNullUndefined = false): data is T {
return typeof data !== 'undefined' && !(considerNullUndefined && data === null);
}
/**
* Checks if the argument is instance of `Object`. Returns false for arrays.
* `not` argument allows to blacklist classes that should be considered as not object.
*/
static isObject<T = Dictionary>(o: any, not: any[] = []): o is T {
return !!o && typeof o === 'object' && !Array.isArray(o) && !not.some(cls => o instanceof cls);
}
/**
* Checks if the argument is string
*/
static isString(s: any): s is string {
return typeof s === 'string';
}
/**
* Checks if the argument is number
*/
static isNumber<T = number>(s: any): s is T {
return typeof s === 'number';
}
/**
* Checks if arguments are deeply (but not strictly) equal.
*/
static equals(a: any, b: any): boolean {
return fastEqual(a, b);
}
/**
* Gets array without duplicates.
*/
static unique<T = string>(items: T[]): T[] {
return [...new Set(items)];
}
/**
* Merges all sources into the target recursively.
*/
static merge(target: any, ...sources: any[]): any {
if (!sources.length) {
return target;
}
const source = sources.shift();
if (Utils.isObject(target) && Utils.isObject(source)) {
Object.entries(source).forEach(([key, value]) => {
if (Utils.isObject(value, [Date, RegExp, Buffer])) {
if (!(key in target)) {
Object.assign(target, { [key]: {} });
}
Utils.merge(target[key], value);
} else {
Object.assign(target, { [key]: value });
}
});
}
return Utils.merge(target, ...sources);
}
static getRootEntity(metadata: MetadataStorage, meta: EntityMetadata): EntityMetadata {
const base = meta.extends && metadata.get(meta.extends, false, false);
if (!base || base === meta) { // make sure we do not fall into infinite loop
return meta;
}
const root = Utils.getRootEntity(metadata, base);
if (root.discriminatorColumn) {
return root;
}
return meta;
}
/**
* Computes difference between two objects, ignoring items missing in `b`.
*/
static diff(a: Dictionary, b: Dictionary): Record<keyof (typeof a & typeof b), any> {
const ret: Dictionary = {};
Object.keys(b).forEach(k => {
if (Utils.equals(a[k], b[k])) {
return;
}
ret[k] = b[k];
});
return ret;
}
/**
* Computes difference between two entities. First calls `prepareEntity` on both, then uses the `diff` method.
*/
static diffEntities<T extends AnyEntity<T>>(a: T, b: T, metadata: MetadataStorage, platform: Platform): EntityData<T> {
return Utils.diff(Utils.prepareEntity(a, metadata, platform), Utils.prepareEntity(b, metadata, platform)) as EntityData<T>;
}
/**
* Removes ORM specific code from entities and prepares it for serializing. Used before change set computation.
* References will be mapped to primary keys, collections to arrays of primary keys.
*/
static prepareEntity<T extends AnyEntity<T>>(entity: T, metadata: MetadataStorage, platform: Platform): EntityData<T> {
if ((entity as Dictionary).__prepared) {
return entity;
}
const meta = metadata.get<T>(entity.constructor.name);
const root = Utils.getRootEntity(metadata, meta);
const ret = {} as EntityData<T>;
if (meta.discriminatorValue) {
ret[root.discriminatorColumn as keyof T] = meta.discriminatorValue as unknown as T[keyof T];
}
// copy all props, ignore collections and references, process custom types
Object.values<EntityProperty<T>>(meta.properties).forEach(prop => {
if (Utils.shouldIgnoreProperty(entity, prop, root)) {
return;
}
if (prop.reference === ReferenceType.EMBEDDED) {
return Object.values<EntityProperty>(meta.properties).filter(p => p.embedded?.[0] === prop.name).forEach(childProp => {
ret[childProp.name as keyof T] = entity[prop.name][childProp.embedded![1]];
});
}
if (Utils.isEntity(entity[prop.name], true)) {
return ret[prop.name] = Utils.getPrimaryKeyValues(entity[prop.name], metadata.get(prop.type).primaryKeys, true);
}
if (prop.customType) {
return ret[prop.name] = prop.customType.convertToDatabaseValue(entity[prop.name], platform);
}
if (Array.isArray(entity[prop.name]) || Utils.isObject(entity[prop.name])) {
return ret[prop.name] = Utils.copy(entity[prop.name]);
}
ret[prop.name] = entity[prop.name];
});
Object.defineProperty(ret, '__prepared', { value: true });
return ret;
}
private static shouldIgnoreProperty<T>(entity: T, prop: EntityProperty<T>, root: EntityMetadata) {
if (!(prop.name in entity) || prop.persist === false) {
return true;
}
const collection = entity[prop.name] as unknown instanceof ArrayCollection;
const noPkRef = Utils.isEntity(entity[prop.name]) && !wrap(entity[prop.name], true).__primaryKeys.every(pk => pk);
const noPkProp = prop.primary && !Utils.isDefined(entity[prop.name], true);
const inverse = prop.reference === ReferenceType.ONE_TO_ONE && !prop.owner;
const discriminator = prop.name === root.discriminatorColumn;
// bidirectional 1:1 and m:1 fields are defined as setters, we need to check for `undefined` explicitly
const isSetter = [ReferenceType.ONE_TO_ONE, ReferenceType.MANY_TO_ONE].includes(prop.reference) && (prop.inversedBy || prop.mappedBy);
const emptyRef = isSetter && entity[prop.name] === undefined;
return collection || noPkProp || noPkRef || inverse || discriminator || emptyRef;
}
/**
* Creates deep copy of given entity.
*/
static copy<T>(entity: T): T {
return clone(entity);
}
/**
* Normalize the argument to always be an array.
*/
static asArray<T>(data?: T | T[]): T[] {
if (typeof data === 'undefined') {
return [];
}
return Array.isArray(data!) ? data : [data!];
}
/**
* Renames object key, keeps order of properties.
*/
static renameKey<T>(payload: T, from: string | keyof T, to: string): void {
if (Utils.isObject(payload) && from in payload && !(to in payload)) {
Object.keys(payload).forEach(key => {
const value = payload[key];
delete payload[key];
payload[from === key ? to : key] = value;
}, payload);
}
}
/**
* Returns array of functions argument names. Uses `acorn` for source code analysis.
*/
static getParamNames(func: { toString(): string } | string, methodName?: string): string[] {
const ret: string[] = [];
const parsed = parse(func.toString());
const checkNode = (node: any, methodName?: string) => {
if (methodName && !(node.key && (node.key as any).name === methodName)) {
return;
}
const params = node.value ? node.value.params : node.params;
ret.push(...params.map((p: any) => {
switch (p.type) {
case 'AssignmentPattern':
return p.left.name;
case 'RestElement':
return '...' + p.argument.name;
default:
return p.name;
}
}));
};
walk(parsed, {
MethodDefinition: (node: any) => checkNode(node, methodName),
FunctionDeclaration: (node: any) => checkNode(node, methodName),
});
return ret;
}
/**
* Checks whether the argument looks like primary key (string, number or ObjectId).
*/
static isPrimaryKey<T>(key: any, allowComposite = false): key is Primary<T> {
if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v))) {
return true;
}
return Utils.isString(key) || typeof key === 'number' || Utils.isObjectID(key) || key instanceof Date;
}
/**
* Extracts primary key from `data`. Accepts objects or primary keys directly.
*/
static extractPK<T extends AnyEntity<T>>(data: any, meta?: EntityMetadata, strict = false): Primary<T> | null {
if (Utils.isPrimaryKey(data)) {
return data as Primary<T>;
}
if (Utils.isEntity(data, true)) {
return wrap(data, true).__primaryKey as Primary<T>;
}
if (strict && meta && Object.keys(data).length !== meta.primaryKeys.length) {
return null;
}
if (Utils.isObject(data) && meta) {
if (meta.compositePK) {
return Utils.getCompositeKeyHash(data, meta) as Primary<T>;
}
return data[meta.primaryKeys[0]] || data[meta.serializedPrimaryKey] || null;
}
return null;
}
static getCompositeKeyHash<T>(entity: T, meta: EntityMetadata<T>): string {
const pks = meta.primaryKeys.map(pk => {
if (Utils.isEntity(entity[pk], true)) {
return wrap(entity[pk], true).__serializedPrimaryKey;
}
return entity[pk];
});
return Utils.getPrimaryKeyHash(pks as string[]);
}
static getPrimaryKeyHash(pks: string[]): string {
return pks.join('~~~');
}
static splitPrimaryKeys(key: string): string[] {
return key.split('~~~');
}
static getPrimaryKeyValue<T extends AnyEntity<T>>(entity: T, primaryKeys: string[]) {
if (primaryKeys.length > 1) {
return Utils.getPrimaryKeyCond(entity, primaryKeys);
}
if (Utils.isEntity(entity[primaryKeys[0]])) {
return wrap(entity[primaryKeys[0]], true).__primaryKey;
}
return entity[primaryKeys[0]];
}
static getPrimaryKeyValues<T extends AnyEntity<T>>(entity: T, primaryKeys: string[], allowScalar = false) {
if (allowScalar && primaryKeys.length === 1) {
if (Utils.isEntity(entity[primaryKeys[0]])) {
return wrap(entity[primaryKeys[0]], true).__primaryKey;
}
return entity[primaryKeys[0]];
}
return primaryKeys.map(pk => {
if (Utils.isEntity(entity[pk])) {
return wrap(entity[pk], true).__primaryKey;
}
return entity[pk];
});
}
static getPrimaryKeyCond<T extends AnyEntity<T>>(entity: T, primaryKeys: string[]): Record<string, Primary<T>> | null {
const cond = primaryKeys.reduce((o, pk) => {
o[pk] = Utils.extractPK(entity[pk]);
return o;
}, {} as any);
if (Object.values(cond).some(v => v === null)) {
return null;
}
return cond;
}
static getPrimaryKeyCondFromArray<T extends AnyEntity<T>>(pks: Primary<T>[], primaryKeys: string[]): Record<string, Primary<T>> {
return primaryKeys.reduce((o, pk, idx) => {
o[pk] = Utils.extractPK(pks[idx]);
return o;
}, {} as any);
}
static getOrderedPrimaryKeys<T extends AnyEntity<T>>(id: Primary<T> | Record<string, Primary<T>>, meta: EntityMetadata<T>): Primary<T>[] {
const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id) as Record<string, Primary<T>>;
return meta.primaryKeys.map(pk => data[pk]) as Primary<T>[];
}
/**
* Checks whether given object is an entity instance.
*/
static isEntity<T = AnyEntity>(data: any, allowReference = false): data is T {
if (allowReference && Utils.isReference(data)) {
return true;
}
return Utils.isObject(data) && !!data.__entity;
}
/**
* Checks whether the argument is instance or `Reference` wrapper.
*/
static isReference<T extends AnyEntity<T>>(data: any): data is Reference<T> {
return data instanceof Reference;
}
/**
* Returns wrapped entity.
*/
static unwrapReference<T extends AnyEntity<T>>(ref: T | Reference<T>): T {
return Utils.isReference<T>(ref) ? (ref as Reference<T>).unwrap() : ref;
}
/**
* Checks whether the argument is ObjectId instance
*/
static isObjectID(key: any) {
return Utils.isObject(key) && key.constructor.name.toLowerCase() === 'objectid';
}
/**
* Checks whether the argument is empty (array without items, object without keys or falsy value).
*/
static isEmpty(data: any): boolean {
if (Array.isArray(data)) {
return data.length === 0;
}
if (Utils.isObject(data)) {
return Object.keys(data).length === 0;
}
return !data;
}
/**
* Gets string name of given class.
*/
static className(classOrName: string | { name: string }): string {
if (Utils.isString(classOrName)) {
return classOrName;
}
return classOrName.name;
}
/**
* Tries to detect `ts-node` runtime.
*/
static detectTsNode(): boolean {
return process.argv[0].endsWith('ts-node') // running via ts-node directly
|| process.argv.slice(1).some(arg => arg.includes('ts-node')) // registering ts-node runner
|| !!require.extensions['.ts'] // check if the extension is registered
|| !!new Error().stack!.split('\n').find(line => line.match(/\w\.ts:\d/)); // as a last resort, try to find a TS file in the stack trace
}
/**
* Uses some dark magic to get source path to caller where decorator is used.
* Analyses stack trace of error created inside the function call.
*/
static lookupPathFromDecorator(stack?: string[]): string {
// use some dark magic to get source path to caller
stack = stack || new Error().stack!.split('\n');
let line = stack.findIndex(line => line.includes('__decorate'))!;
if (line === -1) {
throw new Error('Cannot find path to entity');
}
if (Utils.normalizePath(stack[line]).includes('node_modules/tslib/tslib')) {
line++;
}
const re = stack[line].match(/\(.+\)/i) ? /\((.*):\d+:\d+\)/ : /at\s*(.*):\d+:\d+$/;
return Utils.normalizePath(stack[line].match(re)![1]);
}
/**
* Gets the type of the argument.
*/
static getObjectType(value: any): string {
const objectType = Object.prototype.toString.call(value);
return objectType.match(/\[object (\w+)]/)![1].toLowerCase();
}
/**
* Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
*/
static isPlainObject(value: any): boolean {
if (!Utils.isObject(value)) {
return false;
}
if (typeof value.constructor !== 'function') {
return false;
}
// eslint-disable-next-line no-prototype-builtins
if (!value.constructor.prototype.hasOwnProperty('isPrototypeOf')) {
return false;
}
// most likely plain object
return true;
}
/**
* Wraps the entity in a `Reference` wrapper if the property is defined as `wrappedReference`.
*/
static wrapReference<T extends AnyEntity<T>>(entity: T | Reference<T>, prop: EntityProperty<T>): Reference<T> | T {
if (entity && prop.wrappedReference && !Utils.isReference(entity)) {
return Reference.create(entity as T);
}
return entity;
}
/**
* Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
*/
static async runSerial<T = any, U = any>(items: Iterable<U>, cb: (item: U) => Promise<T>): Promise<T[]> {
const ret = [];
for (const item of items) {
ret.push(await cb(item));
}
return ret;
}
static isCollection(item: any, prop?: EntityProperty, type?: ReferenceType): item is Collection<AnyEntity> {
if (!(item instanceof Collection)) {
return false;
}
return !(prop && type) || prop.reference === type;
}
static normalizePath(...parts: string[]): string {
let path = parts.join('/').replace(/\\/g, '/').replace(/\/$/, '');
path = normalize(path).replace(/\\/g, '/');
return (path.match(/^[/.]|[a-zA-Z]:/) || path.startsWith('!')) ? path : './' + path;
}
static relativePath(path: string, relativeTo: string): string {
if (!path) {
return path;
}
path = Utils.normalizePath(path);
if (path.startsWith('.')) {
return path;
}
path = relative(relativeTo, path);
return Utils.normalizePath(path);
}
static absolutePath(path: string, baseDir = process.cwd()): string {
if (!path) {
return Utils.normalizePath(baseDir);
}
if (!isAbsolute(path)) {
path = baseDir + '/' + path;
}
return Utils.normalizePath(path);
}
static hash(data: string): string {
return createHash('md5').update(data).digest('hex');
}
static runIfNotEmpty(clause: () => any, data: any): void {
if (!Utils.isEmpty(data)) {
clause();
}
}
static defaultValue<T extends Dictionary>(prop: T, option: keyof T, defaultValue: any): void {
prop[option] = option in prop ? prop[option] : defaultValue;
}
static findDuplicates<T>(items: T[]): T[] {
return items.reduce((acc, v, i, arr) => {
return arr.indexOf(v) !== i && acc.indexOf(v) === -1 ? acc.concat(v) : acc;
}, [] as T[]);
}
static randomInt(min: number, max: number): number {
return Math.round(Math.random() * (max - min)) + min;
}
static async pathExists(path: string, options: GlobbyOptions = {}): Promise<boolean> {
if (globby.hasMagic(path)) {
const found = await globby(path, options);
return found.length > 0;
}
return pathExists(path);
}
/**
* Extracts all possible values of a TS enum. Works with both string and numeric enums.
*/
static extractEnumValues(target: Dictionary): (string | number)[] {
const keys = Object.keys(target);
const values = Object.values<string | number>(target);
const numeric = !!values.find(v => typeof v === 'number');
if (numeric) {
return values.filter(val => !keys.includes(val as string));
}
return values;
}
static flatten<T>(arrays: T[][]): T[] {
return ([] as T[]).concat.apply([], arrays);
}
static isOperator(key: string, includeGroupOperators = true): boolean {
if (!includeGroupOperators) {
return !!QueryOperator[key];
}
return !!GroupOperator[key] || !!QueryOperator[key];
}
static getGlobalStorage(namespace: string): Dictionary {
const key = `mikro-orm-${namespace}`;
global[key] = global[key] || {};
return global[key];
}
}