forked from rewiko/crud
/
typeorm-crud.service.ts
1230 lines (1081 loc) · 34.1 KB
/
typeorm-crud.service.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
CreateManyDto,
CrudRequest,
CrudRequestOptions,
CrudService,
CustomOperators,
GetManyDefaultResponse,
JoinOption,
JoinOptions,
QueryOptions,
} from '@dataui/crud';
import {
ComparisonOperator,
ParsedRequestParams,
QueryFilter,
QueryJoin,
QuerySort,
SCondition,
SConditionKey,
} from '@dataui/crud-request';
import {
ClassType,
hasLength,
isArrayFull,
isNil,
isNull,
isObject,
isUndefined,
objKeys,
} from '@dataui/crud-util';
import { oO } from '@zmotivat0r/o0';
import { plainToClass } from 'class-transformer';
import {
Brackets,
ConnectionOptions,
DeepPartial,
EntityMetadata,
ObjectLiteral,
Repository,
SelectQueryBuilder,
WhereExpressionBuilder,
} from 'typeorm';
interface IAllowedRelation {
alias?: string;
nested: boolean;
name: string;
path: string;
columns: string[];
primaryColumns: string[];
allowedColumns: string[];
}
export class TypeOrmCrudService<T> extends CrudService<T, DeepPartial<T>> {
protected dbName: ConnectionOptions['type'];
protected entityColumns: string[];
protected entityPrimaryColumns: string[];
protected entityHasDeleteColumn: boolean = false;
protected entityColumnsHash: ObjectLiteral = {};
protected entityRelationsHash: Map<string, IAllowedRelation> = new Map();
protected sqlInjectionRegEx: RegExp[] = [
/(%27)|(\')|(--)|(%23)|(#)/gi,
/((%3D)|(=))[^\n]*((%27)|(\')|(--)|(%3B)|(;))/gi,
/w*((%27)|(\'))((%6F)|o|(%4F))((%72)|r|(%52))/gi,
/((%27)|(\'))union/gi,
];
constructor(protected repo: Repository<T>) {
super();
this.dbName = this.repo.metadata.connection.options.type;
this.onInitMapEntityColumns();
}
public get findOne(): Repository<T>['findOne'] {
return this.repo.findOne.bind(this.repo);
}
public get findOneBy(): Repository<T>['findOneBy'] {
return this.repo.findOneBy.bind(this.repo);
}
public get find(): Repository<T>['find'] {
return this.repo.find.bind(this.repo);
}
public get count(): Repository<T>['count'] {
return this.repo.count.bind(this.repo);
}
protected get entityType(): ClassType<T> {
return this.repo.target as ClassType<T>;
}
protected get alias(): string {
return this.repo.metadata.targetName;
}
/**
* Get many
* @param req
*/
public async getMany(req: CrudRequest): Promise<GetManyDefaultResponse<T> | T[]> {
const { parsed, options } = req;
const builder = await this.createBuilder(parsed, options);
return this.doGetMany(builder, parsed, options);
}
/**
* Get one
* @param req
*/
public async getOne(req: CrudRequest): Promise<T> {
return this.getOneOrFail(req);
}
/**
* Create one
* @param req
* @param dto
*/
public async createOne(req: CrudRequest, dto: DeepPartial<T>): Promise<T> {
const { returnShallow } = req.options.routes.createOneBase;
const entity = this.prepareEntityBeforeSave(dto, req.parsed);
/* istanbul ignore if */
if (!entity) {
this.throwBadRequestException(`Empty data. Nothing to save.`);
}
const saved = await this.repo.save<any>(entity);
if (returnShallow) {
return saved;
} else {
const primaryParams = this.getPrimaryParams(req.options);
/* istanbul ignore next */
if (!primaryParams.length && primaryParams.some((p) => isNil(saved[p]))) {
return saved;
} else {
req.parsed.search = primaryParams.reduce(
(acc, p) => ({ ...acc, [p]: saved[p] }),
{},
);
return this.getOneOrFail(req);
}
}
}
/**
* Create many
* @param req
* @param dto
*/
public async createMany(
req: CrudRequest,
dto: CreateManyDto<DeepPartial<T>>,
): Promise<T[]> {
/* istanbul ignore if */
if (!isObject(dto) || !isArrayFull(dto.bulk)) {
this.throwBadRequestException(`Empty data. Nothing to save.`);
}
const bulk = dto.bulk
.map((one) => this.prepareEntityBeforeSave(one, req.parsed))
.filter((d) => !isUndefined(d));
/* istanbul ignore if */
if (!hasLength(bulk)) {
this.throwBadRequestException(`Empty data. Nothing to save.`);
}
return this.repo.save<any>(bulk, { chunk: 50 });
}
/**
* Update one
* @param req
* @param dto
*/
public async updateOne(req: CrudRequest, dto: DeepPartial<T>): Promise<T> {
const { allowParamsOverride, returnShallow } = req.options.routes.updateOneBase;
const paramsFilters = this.getParamFilters(req.parsed);
// disable cache while updating
req.options.query.cache = false;
const found = await this.getOneOrFail(req, returnShallow);
const toSave = !allowParamsOverride
? { ...found, ...dto, ...paramsFilters, ...req.parsed.authPersist }
: { ...found, ...dto, ...req.parsed.authPersist };
const updated = await this.repo.save(
plainToClass(
this.entityType,
toSave,
req.parsed.classTransformOptions,
) as unknown as DeepPartial<T>,
);
if (returnShallow) {
return updated;
} else {
req.parsed.paramsFilter.forEach((filter) => {
filter.value = updated[filter.field];
});
return this.getOneOrFail(req);
}
}
/**
* Recover one
* @param req
* @param dto
*/
public async recoverOne(req: CrudRequest): Promise<T> {
// disable cache while recovering
req.options.query.cache = false;
const found = await this.getOneOrFail(req, false, true);
return this.repo.recover(found as DeepPartial<T>);
}
/**
* Replace one
* @param req
* @param dto
*/
public async replaceOne(req: CrudRequest, dto: DeepPartial<T>): Promise<T> {
const { allowParamsOverride, returnShallow } = req.options.routes.replaceOneBase;
const paramsFilters = this.getParamFilters(req.parsed);
// disable cache while replacing
req.options.query.cache = false;
const [_, found] = await oO(this.getOneOrFail(req, returnShallow));
const toSave = !allowParamsOverride
? { ...(found || {}), ...dto, ...paramsFilters, ...req.parsed.authPersist }
: {
...(found || /* istanbul ignore next */ {}),
...paramsFilters,
...dto,
...req.parsed.authPersist,
};
const replaced = await this.repo.save(
plainToClass(
this.entityType,
toSave,
req.parsed.classTransformOptions,
) as unknown as DeepPartial<T>,
);
if (returnShallow) {
return replaced;
} else {
const primaryParams = this.getPrimaryParams(req.options);
/* istanbul ignore if */
if (!primaryParams.length) {
return replaced;
}
req.parsed.search = primaryParams.reduce(
(acc, p) => ({ ...acc, [p]: replaced[p] }),
{},
);
return this.getOneOrFail(req);
}
}
/**
* Delete one
* @param req
*/
public async deleteOne(req: CrudRequest): Promise<void | T> {
const { returnDeleted } = req.options.routes.deleteOneBase;
// disable cache while deleting
req.options.query.cache = false;
const found = await this.getOneOrFail(req, returnDeleted);
const toReturn = returnDeleted
? plainToClass(this.entityType, { ...found }, req.parsed.classTransformOptions)
: undefined;
const deleted =
req.options.query.softDelete === true
? await this.repo.softRemove(found as DeepPartial<T>)
: await this.repo.remove(found);
return toReturn;
}
public getParamFilters(parsed: CrudRequest['parsed']): ObjectLiteral {
const filters = {};
/* istanbul ignore else */
if (hasLength(parsed.paramsFilter)) {
for (const filter of parsed.paramsFilter) {
filters[filter.field] = filter.value;
}
}
return filters;
}
/**
* Create TypeOrm QueryBuilder
* @param parsed
* @param options
* @param many
*/
public async createBuilder(
parsed: ParsedRequestParams,
options: CrudRequestOptions,
many = true,
withDeleted = false,
): Promise<SelectQueryBuilder<T>> {
// create query builder
const builder = this.repo.createQueryBuilder(this.alias);
// get select fields
const select = this.getSelect(parsed, options.query);
// select fields
builder.select(select);
// if soft deleted is enabled add where statement to filter deleted records
if (this.entityHasDeleteColumn && options.query.softDelete) {
if (parsed.includeDeleted === 1 || withDeleted) {
builder.withDeleted();
}
}
// search
this.setSearchCondition(builder, parsed.search, options.operators?.custom);
// set joins
const joinOptions = options.query?.join || {};
const allowedJoins = objKeys(joinOptions);
if (hasLength(allowedJoins)) {
const eagerJoins: any = {};
for (let i = 0; i < allowedJoins.length; i++) {
/* istanbul ignore else */
if (joinOptions[allowedJoins[i]].eager) {
const cond = parsed.join.find((j) => j && j.field === allowedJoins[i]) || {
field: allowedJoins[i],
};
this.setJoin(cond, joinOptions, builder);
eagerJoins[allowedJoins[i]] = true;
}
}
if (isArrayFull(parsed.join)) {
for (let i = 0; i < parsed.join.length; i++) {
/* istanbul ignore else */
if (!eagerJoins[parsed.join[i].field]) {
this.setJoin(parsed.join[i], joinOptions, builder);
}
}
}
}
/* istanbul ignore else */
if (many) {
// set sort (order by)
const sort = this.getSort(parsed, options.query);
builder.orderBy(sort);
// set take
const take = this.getTake(parsed, options.query);
/* istanbul ignore else */
if (isFinite(take)) {
builder.take(take);
}
// set skip
const skip = this.getSkip(parsed, take);
/* istanbul ignore else */
if (isFinite(skip)) {
builder.skip(skip);
}
}
// set cache
/* istanbul ignore else */
if (options.query.cache && parsed.cache !== 0) {
builder.cache(options.query.cache);
}
return builder;
}
/**
* depends on paging call `SelectQueryBuilder#getMany` or `SelectQueryBuilder#getManyAndCount`
* helpful for overriding `TypeOrmCrudService#getMany`
* @see getMany
* @see SelectQueryBuilder#getMany
* @see SelectQueryBuilder#getManyAndCount
* @param builder
* @param query
* @param options
*/
protected async doGetMany(
builder: SelectQueryBuilder<T>,
query: ParsedRequestParams,
options: CrudRequestOptions,
): Promise<GetManyDefaultResponse<T> | T[]> {
if (this.decidePagination(query, options)) {
const [data, total] = await builder.getManyAndCount();
const limit = builder.expressionMap.take;
const offset = builder.expressionMap.skip;
return this.createPageInfo(data, total, limit || total, offset || 0);
}
return builder.getMany();
}
protected onInitMapEntityColumns() {
this.entityColumns = this.repo.metadata.columns.map((prop) => {
// In case column is an embedded, use the propertyPath to get complete path
if (prop.embeddedMetadata) {
this.entityColumnsHash[prop.propertyPath] = prop.databasePath;
return prop.propertyPath;
}
this.entityColumnsHash[prop.propertyName] = prop.databasePath;
return prop.propertyName;
});
this.entityPrimaryColumns = this.repo.metadata.columns
.filter((prop) => prop.isPrimary)
.map((prop) => prop.propertyName);
this.entityHasDeleteColumn =
this.repo.metadata.columns.filter((prop) => prop.isDeleteDate).length > 0;
}
protected async getOneOrFail(
req: CrudRequest,
shallow = false,
withDeleted = false,
): Promise<T> {
const { parsed, options } = req;
const builder = shallow
? this.repo.createQueryBuilder(this.alias)
: await this.createBuilder(parsed, options, true, withDeleted);
if (shallow) {
this.setSearchCondition(builder, parsed.search, options.operators?.custom);
}
const found = withDeleted
? await builder.withDeleted().getOne()
: await builder.getOne();
if (!found) {
this.throwNotFoundException(this.alias);
}
return found;
}
protected prepareEntityBeforeSave(
dto: DeepPartial<T>,
parsed: CrudRequest['parsed'],
): T {
/* istanbul ignore if */
if (!isObject(dto)) {
return undefined;
}
if (hasLength(parsed.paramsFilter)) {
for (const filter of parsed.paramsFilter) {
dto[filter.field] = filter.value;
}
}
/* istanbul ignore if */
if (!hasLength(objKeys(dto))) {
return undefined;
}
return dto instanceof this.entityType
? Object.assign(dto, parsed.authPersist)
: plainToClass(
this.entityType,
{ ...dto, ...parsed.authPersist },
parsed.classTransformOptions,
);
}
protected getAllowedColumns(columns: string[], options: QueryOptions): string[] {
return (!options.exclude || !options.exclude.length) &&
(!options.allow || /* istanbul ignore next */ !options.allow.length)
? columns
: columns.filter(
(column) =>
(options.exclude && options.exclude.length
? !options.exclude.some((col) => col === column)
: /* istanbul ignore next */ true) &&
(options.allow && options.allow.length
? options.allow.some((col) => col === column)
: /* istanbul ignore next */ true),
);
}
protected getEntityColumns(entityMetadata: EntityMetadata): {
columns: string[];
primaryColumns: string[];
} {
const columns =
entityMetadata.columns.map((prop) => prop.propertyPath) ||
/* istanbul ignore next */ [];
const primaryColumns =
entityMetadata.primaryColumns.map((prop) => prop.propertyPath) ||
/* istanbul ignore next */ [];
return { columns, primaryColumns };
}
protected getRelationMetadata(field: string, options: JoinOption): IAllowedRelation {
try {
let allowedRelation;
let nested = false;
if (this.entityRelationsHash.has(field)) {
allowedRelation = this.entityRelationsHash.get(field);
} else {
const fields = field.split('.');
let relationMetadata: EntityMetadata;
let name: string;
let path: string;
let parentPath: string;
if (fields.length === 1) {
const found = this.repo.metadata.relations.find(
(one) => one.propertyName === fields[0],
);
if (found) {
name = fields[0];
path = `${this.alias}.${fields[0]}`;
relationMetadata = found.inverseEntityMetadata;
}
} else {
nested = true;
parentPath = '';
const reduced = fields.reduce(
(res, propertyName: string, i) => {
const found = res.relations.length
? res.relations.find((one) => one.propertyName === propertyName)
: null;
relationMetadata = found ? found.inverseEntityMetadata : null;
const relations = relationMetadata ? relationMetadata.relations : [];
name = propertyName;
if (i !== fields.length - 1) {
parentPath = !parentPath
? propertyName
: /* istanbul ignore next */ `${parentPath}.${propertyName}`;
}
return {
relations,
relationMetadata,
};
},
{
relations: this.repo.metadata.relations,
relationMetadata: null,
},
);
relationMetadata = reduced.relationMetadata;
}
if (relationMetadata) {
const { columns, primaryColumns } = this.getEntityColumns(relationMetadata);
if (!path && parentPath) {
const parentAllowedRelation = this.entityRelationsHash.get(parentPath);
/* istanbul ignore next */
if (parentAllowedRelation) {
path = parentAllowedRelation.alias
? `${parentAllowedRelation.alias}.${name}`
: field;
}
}
allowedRelation = {
alias: options.alias,
name,
path,
columns,
nested,
primaryColumns,
};
}
}
if (allowedRelation) {
const allowedColumns = this.getAllowedColumns(allowedRelation.columns, options);
const toSave: IAllowedRelation = { ...allowedRelation, allowedColumns };
this.entityRelationsHash.set(field, toSave);
if (options.alias) {
this.entityRelationsHash.set(options.alias, toSave);
}
return toSave;
}
} catch (_) {
/* istanbul ignore next */
return null;
}
}
protected setJoin(
cond: QueryJoin,
joinOptions: JoinOptions,
builder: SelectQueryBuilder<T>,
) {
const options = joinOptions[cond.field];
if (!options) {
console.warn(
'relation "' +
cond.field +
'" not found in allowed relations in the controller. Did you mean to use one of these? [' +
Object.keys(joinOptions).join(', ') +
']',
);
return true;
}
const allowedRelation = this.getRelationMetadata(cond.field, options);
if (!allowedRelation) {
return true;
}
const relationType = options.required ? 'innerJoin' : 'leftJoin';
const alias = options.alias ? options.alias : allowedRelation.name;
builder[relationType](allowedRelation.path, alias);
if (options.select !== false) {
const columns = isArrayFull(cond.select)
? cond.select.filter((column) =>
allowedRelation.allowedColumns.some((allowed) => allowed === column),
)
: allowedRelation.allowedColumns;
const select = [
...new Set([
...allowedRelation.primaryColumns,
...(isArrayFull(options.persist) ? options.persist : []),
...columns,
]),
].map((col) => `${alias}.${col}`);
builder.addSelect(Array.from(new Set(select)));
}
}
protected setAndWhere(
cond: QueryFilter,
i: any,
builder: SelectQueryBuilder<T> | WhereExpressionBuilder,
customOperators: CustomOperators,
) {
const { str, params } = this.mapOperatorsToQuery(
cond,
`andWhere${i}`,
customOperators,
);
builder.andWhere(str, params);
}
protected setOrWhere(
cond: QueryFilter,
i: any,
builder: SelectQueryBuilder<T> | WhereExpressionBuilder,
customOperators: CustomOperators,
) {
const { str, params } = this.mapOperatorsToQuery(
cond,
`orWhere${i}`,
customOperators,
);
builder.orWhere(str, params);
}
protected setSearchCondition(
builder: SelectQueryBuilder<T>,
search: SCondition,
customOperators: CustomOperators,
condition: SConditionKey = '$and',
) {
/* istanbul ignore else */
if (isObject(search)) {
const keys = objKeys(search);
/* istanbul ignore else */
if (keys.length) {
// search: {$not: [...]}
if (isArrayFull(search.$not)) {
this.builderAddBrackets(
builder,
condition,
new Brackets((qb: any) => {
search.$not.forEach((item: any) => {
this.setSearchCondition(qb, item, customOperators, '$and');
});
}),
true,
);
}
// search: {$and: [...], ...}
else if (isArrayFull(search.$and)) {
// search: {$and: [{}]}
if (search.$and.length === 1) {
this.setSearchCondition(builder, search.$and[0], customOperators, condition);
}
// search: {$and: [{}, {}, ...]}
else {
this.builderAddBrackets(
builder,
condition,
new Brackets((qb: any) => {
search.$and.forEach((item: any) => {
this.setSearchCondition(qb, item, customOperators, '$and');
});
}),
);
}
}
// search: {$or: [...], ...}
else if (isArrayFull(search.$or)) {
// search: {$or: [...]}
if (keys.length === 1) {
// search: {$or: [{}]}
if (search.$or.length === 1) {
this.setSearchCondition(builder, search.$or[0], customOperators, condition);
}
// search: {$or: [{}, {}, ...]}
else {
this.builderAddBrackets(
builder,
condition,
new Brackets((qb: any) => {
search.$or.forEach((item: any) => {
this.setSearchCondition(qb, item, customOperators, '$or');
});
}),
);
}
}
// search: {$or: [...], foo, ...}
else {
this.builderAddBrackets(
builder,
condition,
new Brackets((qb: any) => {
keys.forEach((field: string) => {
if (field !== '$or') {
const value = search[field];
if (!isObject(value)) {
this.builderSetWhere(qb, '$and', field, value, customOperators);
} else {
this.setSearchFieldObjectCondition(
qb,
'$and',
field,
value,
customOperators,
);
}
} else {
if (search.$or.length === 1) {
this.setSearchCondition(
builder,
search.$or[0],
customOperators,
'$and',
);
} else {
this.builderAddBrackets(
qb,
'$and',
new Brackets((qb2: any) => {
search.$or.forEach((item: any) => {
this.setSearchCondition(qb2, item, customOperators, '$or');
});
}),
);
}
}
});
}),
);
}
}
// search: {...}
else {
// search: {foo}
if (keys.length === 1) {
const field = keys[0];
const value = search[field];
if (!isObject(value)) {
this.builderSetWhere(builder, condition, field, value, customOperators);
} else {
this.setSearchFieldObjectCondition(
builder,
condition,
field,
value,
customOperators,
);
}
}
// search: {foo, ...}
else {
this.builderAddBrackets(
builder,
condition,
new Brackets((qb: any) => {
keys.forEach((field: string) => {
const value = search[field];
if (!isObject(value)) {
this.builderSetWhere(qb, '$and', field, value, customOperators);
} else {
this.setSearchFieldObjectCondition(
qb,
'$and',
field,
value,
customOperators,
);
}
});
}),
);
}
}
}
}
}
protected builderAddBrackets(
builder: SelectQueryBuilder<T>,
condition: SConditionKey,
brackets: Brackets,
negated: boolean = false,
) {
if (negated) {
// No builtin support for not, this is copied from QueryBuilder.getWhereCondition
const whereQueryBuilder = builder.createQueryBuilder();
(whereQueryBuilder as any).parentQueryBuilder = builder;
whereQueryBuilder.expressionMap.mainAlias = builder.expressionMap.mainAlias;
whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
builder.expressionMap.aliasNamePrefixingEnabled;
whereQueryBuilder.expressionMap.parameters = builder.expressionMap.parameters;
whereQueryBuilder.expressionMap.nativeParameters =
builder.expressionMap.nativeParameters;
whereQueryBuilder.expressionMap.wheres = [];
brackets.whereFactory(whereQueryBuilder as any);
const wheres = {
operator: 'brackets',
condition: whereQueryBuilder.expressionMap.wheres,
};
const type = condition === '$and' ? 'and' : condition === '$or' ? 'or' : 'simple';
builder.expressionMap.wheres.push({
type,
condition: {
operator: 'not',
condition: wheres as any,
},
});
} else if (condition === '$and') {
builder.andWhere(brackets);
} else {
builder.orWhere(brackets);
}
}
protected builderSetWhere(
builder: SelectQueryBuilder<T>,
condition: SConditionKey,
field: string,
value: any,
customOperators: CustomOperators,
operator: ComparisonOperator = '$eq',
) {
const time = process.hrtime();
// const index = `${field}${time[0]}${time[1]}`;
/**
* Correcting the Error [Invalid Column Name] or [ syntax error at or near \":\".]
* When using filter or search in relational/nested entities.
*/
const safeFieldName = field.replace(/./g, '_');
const index = `${safeFieldName}${time[0]}${time[1]}`;
const args = [
{ field, operator: isNull(value) ? '$isnull' : operator, value },
index,
builder,
customOperators,
];
const fn = condition === '$and' ? this.setAndWhere : this.setOrWhere;
fn.apply(this, args);
}
protected setSearchFieldObjectCondition(
builder: SelectQueryBuilder<T>,
condition: SConditionKey,
field: string,
object: any,
customOperators: CustomOperators,
) {
/* istanbul ignore else */
if (isObject(object)) {
const operators = objKeys(object);
if (operators.length === 1 && operators[0] !== '$or') {
const operator = operators[0] as ComparisonOperator;
const value = object[operator];
this.builderSetWhere(builder, condition, field, value, customOperators, operator);
} else {
this.builderAddBrackets(
builder,
condition,
new Brackets((qb: any) => {
operators.forEach((operator: ComparisonOperator) => {
const value = object[operator];
if (operator !== '$or') {
this.builderSetWhere(
qb,
condition,
field,
value,
customOperators,
operator,
);
} else {
const orKeys = objKeys(object.$or);
if (orKeys.length === 1) {
this.setSearchFieldObjectCondition(
qb,
condition,
field,
object.$or,
customOperators,
);
} else {
this.builderAddBrackets(
qb,
condition,
new Brackets((qb2: any) => {
this.setSearchFieldObjectCondition(
qb2,
'$or',
field,
object.$or,
customOperators,
);
}),
);
}
}
});
}),
);
}
}
}
protected getSelect(query: ParsedRequestParams, options: QueryOptions): string[] {
const allowed = this.getAllowedColumns(this.entityColumns, options);
const columns =
query.fields && query.fields.length
? query.fields.filter((field) => allowed.some((col) => field === col))
: allowed;
const select = [
...new Set([
...(options.persist && options.persist.length ? options.persist : []),
...columns,
...this.entityPrimaryColumns,
]),
].map((col) => `${this.alias}.${col}`);
return Array.from(new Set(select));
}
protected getSort(query: ParsedRequestParams, options: QueryOptions) {