@simitgroup/simpleapp-generator 1.6.7-i-alpha → 1.6.7-k-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,48 +4,25 @@
4
4
  * last change 2024-01-27
5
5
  * Author: Ks Tan
6
6
  */
7
- import { Injectable, Logger, Inject } from '@nestjs/common';
8
- import { InjectModel } from '@nestjs/mongoose';
7
+ import { Inject, Injectable, Logger } from '@nestjs/common';
9
8
  import jsonpath from 'jsonpath';
10
9
  import _ from 'lodash';
11
10
 
12
- import { AuditTrail } from '../commons/audittrail.service';
13
- import { foreignkeys } from '../commons/dicts/foreignkeys';
11
+ import { BadRequestException, ForbiddenException, HttpExceptionOptions, InternalServerErrorException, NotFoundException } from '@nestjs/common/exceptions';
14
12
  import { EventEmitter2 } from '@nestjs/event-emitter';
15
- import {
16
- Model,
17
- Types,
18
- PipelineStage,
19
- mongo,
20
- FilterQuery,
21
- ProjectionType,
22
- } from 'mongoose';
23
13
  import Ajv from 'ajv';
24
- import addFormats from 'ajv-formats';
25
14
  import addErrors from 'ajv-errors';
26
- import {
27
- NotFoundException,
28
- HttpException,
29
- BadRequestException,
30
- ForbiddenException,
31
- InternalServerErrorException,
32
- HttpExceptionOptions,
33
- } from '@nestjs/common/exceptions';
34
- import { UserContext } from '../commons/user.context';
15
+ import addFormats from 'ajv-formats';
16
+ import { FilterQuery, Model, PipelineStage, mongo } from 'mongoose';
35
17
  import { CloudApiService } from 'src/cloudapi/cloudapi.service';
18
+ import { CustomException } from 'src/customexception';
36
19
  import { PrintApiService } from 'src/printapi/printapi.service';
20
+ import { AuditTrail } from '../commons/audittrail.service';
21
+ import { foreignkeys } from '../commons/dicts/foreignkeys';
37
22
  import { DocNumberFormatGenerator } from '../commons/docnogenerator.service';
38
23
  import { RunWebhookService } from '../commons/runwebhook.service';
39
- import {
40
- IsolationType,
41
- DefaultHooks,
42
- MoreProjectionType,
43
- DeleteResultType,
44
- WorkflowName,
45
- TextSearchBody,
46
- CheckMutipleUnionExistResponse,
47
- } from '../types';
48
- import { CustomException } from 'src/customexception';
24
+ import { UserContext } from '../commons/user.context';
25
+ import { CheckMutipleUnionExistResponse, DefaultHooks, DeleteResultType, IsolationType, MoreProjectionType, TextSearchBody, WorkflowName } from '../types';
49
26
 
50
27
  @Injectable()
51
28
  export class SimpleAppService<T extends { _id?: string; __v?: number }> {
@@ -56,7 +33,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
56
33
  @Inject(PrintApiService)
57
34
  protected printapi: PrintApiService;
58
35
  @Inject(RunWebhookService)
59
- protected runWebHook:RunWebhookService;
36
+ protected runWebHook: RunWebhookService;
60
37
  protected hooks: DefaultHooks<T> = {};
61
38
  protected logger = new Logger();
62
39
  protected strictIsolation = true;
@@ -88,12 +65,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
88
65
 
89
66
  // protected userprovider = new UserContext() ;
90
67
 
91
- constructor(
92
- doctype: string,
93
- docname: string,
94
- newdoc: Model<T>,
95
- isolationtype: IsolationType = IsolationType.org,
96
- ) {
68
+ constructor(doctype: string, docname: string, newdoc: Model<T>, isolationtype: IsolationType = IsolationType.org) {
97
69
  // console.log("-------init simpleapp service abstract class -------userprovider=",typeof this.userprovider)
98
70
  this.documentType = doctype.toUpperCase();
99
71
  this.documentName = docname;
@@ -104,8 +76,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
104
76
  // this.tenantdoc = tenantdoc
105
77
  }
106
78
  getDocumentType = () => this.documentType;
107
- getDocumentName = (capFirst: boolean = false) =>
108
- capFirst ? _.upperFirst(this.documentName) : this.documentName;
79
+ getDocumentName = (capFirst: boolean = false) => (capFirst ? _.upperFirst(this.documentName) : this.documentName);
109
80
  getRecordId = (): string => this.data._id;
110
81
  setSchema = (newschema) => (this.jsonschema = newschema);
111
82
  getSchema = () => this.doc.schema.obj;
@@ -173,10 +144,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
173
144
  const filter1 = {};
174
145
  const filter2 = {};
175
146
  const filters: any[] = [];
176
- if (
177
- this.jsonschema.properties[this.documentIdentityCode]['type'] ==
178
- 'string'
179
- ) {
147
+ if (this.jsonschema.properties[this.documentIdentityCode]['type'] == 'string') {
180
148
  filter1[this.documentIdentityCode] = { $regex: keyword, $options: 'i' };
181
149
  filters.push(filter1);
182
150
  }
@@ -213,14 +181,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
213
181
  */
214
182
  async searchNoIsolation(appuser: UserContext, filters: FilterQuery<T>) {
215
183
  try {
216
- if (this.hooks.beforeSearch)
217
- await this.hooks.beforeSearch(appuser, filters);
184
+ if (this.hooks.beforeSearch) await this.hooks.beforeSearch(appuser, filters);
218
185
  const products = await this.doc.find(filters);
219
186
  const productlist = products.map((p) => {
220
187
  return p;
221
188
  });
222
- if (this.hooks.afterSearch)
223
- await this.hooks.afterSearch(appuser, productlist);
189
+ if (this.hooks.afterSearch) await this.hooks.afterSearch(appuser, productlist);
224
190
 
225
191
  // console.log(products);
226
192
  return productlist;
@@ -241,9 +207,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
241
207
  throw new InternalServerErrorException(err);
242
208
  }
243
209
  } else {
244
- throw new InternalServerErrorException(
245
- 'first aggregate pipelinestage shall use $match',
246
- );
210
+ throw new InternalServerErrorException('first aggregate pipelinestage shall use $match');
247
211
  }
248
212
  }
249
213
  async aggregate(appuser: UserContext, pipeline: PipelineStage[]) {
@@ -261,18 +225,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
261
225
  throw new InternalServerErrorException(err);
262
226
  }
263
227
  } else {
264
- throw new InternalServerErrorException(
265
- 'first aggregate pipelinestage shall use $match',
266
- );
228
+ throw new InternalServerErrorException('first aggregate pipelinestage shall use $match');
267
229
  }
268
230
  }
269
- async search(
270
- appuser: UserContext,
271
- filters: FilterQuery<T>,
272
- projection: string[] = undefined,
273
- sort: any = undefined,
274
- lookup: { [key: string]: string } = undefined,
275
- ) {
231
+ async search(appuser: UserContext, filters: FilterQuery<T>, projection: string[] = undefined, sort: any = undefined, lookup: { [key: string]: string } = undefined) {
276
232
  try {
277
233
  const isolationFilter = { ...this.getIsolationFilter(appuser) };
278
234
  this.polishIsolationFilter(isolationFilter);
@@ -280,24 +236,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
280
236
  // console.log("initial search",filters)
281
237
  const newfilters: FilterQuery<T> = { ...filters, ...isolationFilter };
282
238
 
283
- if (this.hooks.beforeSearch)
284
- await this.hooks.beforeSearch(appuser, newfilters);
239
+ if (this.hooks.beforeSearch) await this.hooks.beforeSearch(appuser, newfilters);
285
240
  // console.log("before _find",newfilters)
286
241
  // console.log("this.doc",this.doc)
287
242
  let searchResults: T[] = [];
288
243
  if (lookup === undefined) {
289
244
  this.logger.debug('after search', newfilters);
290
- searchResults = await this.doc
291
- .find(newfilters, projection, { session: appuser.getDBSession() })
292
- .sort(sort);
245
+ searchResults = await this.doc.find(newfilters, projection, { session: appuser.getDBSession() }).sort(sort);
293
246
  } else {
294
- const pipelines = this.searchToAggregate(
295
- appuser,
296
- newfilters,
297
- projection,
298
- sort,
299
- lookup,
300
- );
247
+ const pipelines = this.searchToAggregate(appuser, newfilters, projection, sort, lookup);
301
248
  this.logger.debug('after aggregate', pipelines);
302
249
  searchResults = await this.aggregate(appuser, pipelines);
303
250
  }
@@ -326,20 +273,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
326
273
  const orConditions: any[] = [];
327
274
  if (body.fields && body.fields.length > 0) {
328
275
  body.fields.forEach((field: string) => {
329
- if (
330
- field != 'defaultPrice' &&
331
- field != 'amount' &&
332
- field != 'active' &&
333
- field != 'updated'
334
- ) {
276
+ if (field != 'defaultPrice' && field != 'amount' && field != 'active' && field != 'updated') {
335
277
  orConditions.push({
336
278
  [field]: { $regex: keyword, $options: 'i' },
337
279
  });
338
280
  } else {
339
- if (
340
- !isNaN(Number(keyword)) &&
341
- (field == 'defaultPrice' || field == 'amount')
342
- ) {
281
+ if (!isNaN(Number(keyword)) && (field == 'defaultPrice' || field == 'amount')) {
343
282
  orConditions.push({
344
283
  [field]: { $gte: keyword },
345
284
  });
@@ -360,10 +299,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
360
299
  const sorts = body.sorts || {};
361
300
 
362
301
  // Ensure `this.doc` is a Mongoose model or similar
363
- const results = await this.doc
364
- .find(newfilters, fields)
365
- .sort(sorts)
366
- .exec();
302
+ const results = await this.doc.find(newfilters, fields).sort(sorts).exec();
367
303
 
368
304
  return results;
369
305
  } catch (error) {
@@ -373,12 +309,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
373
309
  }
374
310
  }
375
311
  async findById(appuser: UserContext, id: string) {
376
- if (this.hooks.beforeFetchRecord)
377
- await this.hooks.beforeFetchRecord(appuser, id);
312
+ if (this.hooks.beforeFetchRecord) await this.hooks.beforeFetchRecord(appuser, id);
378
313
 
379
314
  const data = await this.search(appuser, { _id: id as any });
380
- if (this.hooks.afterFetchRecord)
381
- await this.hooks.afterFetchRecord(appuser, data[0]);
315
+ if (this.hooks.afterFetchRecord) await this.hooks.afterFetchRecord(appuser, data[0]);
382
316
 
383
317
  if (data.length == 1) {
384
318
  // console.log('data0', data[0]);
@@ -389,12 +323,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
389
323
  }
390
324
 
391
325
  async findByIdNoIsolation(appuser: UserContext, id: string) {
392
- if (this.hooks.beforeFetchRecord)
393
- await this.hooks.beforeFetchRecord(appuser, id);
326
+ if (this.hooks.beforeFetchRecord) await this.hooks.beforeFetchRecord(appuser, id);
394
327
 
395
328
  const data = await this.searchNoIsolation(appuser, { _id: id as any });
396
- if (this.hooks.afterFetchRecord)
397
- await this.hooks.afterFetchRecord(appuser, data[0]);
329
+ if (this.hooks.afterFetchRecord) await this.hooks.afterFetchRecord(appuser, data[0]);
398
330
 
399
331
  if (data.length == 1) {
400
332
  // console.log('data0', data[0]);
@@ -406,6 +338,11 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
406
338
 
407
339
  async createManyWithId(appuser: UserContext, datas: T[]) {
408
340
  if (Array.isArray(datas)) {
341
+ const dbsession = appuser.getDBSession();
342
+ if (dbsession && !dbsession.inTransaction()) {
343
+ dbsession.startTransaction({ readPreference: 'primary' });
344
+ }
345
+
409
346
  for (let i = 0; i < datas.length; i++) {
410
347
  const data = datas[i];
411
348
  let isolationFilter: any = { ...appuser.getCreateFilterWithId() };
@@ -417,18 +354,14 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
417
354
  this.applyNestedDateTime(appuser, data, 'create');
418
355
  }
419
356
 
420
- const result = await this.doc.insertMany(datas);
421
- await this.audittrail.addManyEvents(
422
- appuser,
423
- this.documentName,
424
- 'createMany',
425
- datas,
426
- );
357
+ const result = await this.doc.insertMany(datas, { session: dbsession });
358
+ await this.audittrail.addManyEvents(appuser, this.documentName, 'createMany', datas);
359
+ for (let i = 0; i < datas.length; i++) {
360
+ appuser.addInsertedRecordId(this.documentName, datas[i]._id);
361
+ }
427
362
  return result;
428
363
  } else {
429
- throw new BadRequestException(
430
- this.getDocumentType() + ': create many only support array',
431
- );
364
+ throw new BadRequestException(this.getDocumentType() + ': create many only support array');
432
365
  }
433
366
  }
434
367
 
@@ -445,7 +378,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
445
378
  let result;
446
379
  const dbsession = appuser.getDBSession();
447
380
  if (dbsession && !dbsession.inTransaction()) {
448
- dbsession.startTransaction();
381
+ dbsession.startTransaction({ readPreference: 'primary' });
449
382
  }
450
383
 
451
384
  if (this.withDocNumberFormat && !data[this.documentIdentityCode]) {
@@ -459,29 +392,18 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
459
392
  this.reCalculateValue(data);
460
393
  await this.validateData(appuser, data);
461
394
  this.applyNestedDateTime(appuser, data, 'create');
462
- if (this.hooks.beforeCreate)
463
- await this.hooks.beforeCreate(appuser, data);
395
+ if (this.hooks.beforeCreate) await this.hooks.beforeCreate(appuser, data);
464
396
  const newdoc = new this.doc(data);
465
397
 
466
398
  try {
467
399
  result = await newdoc.save({ session: dbsession });
468
- await this.audittrail.addEvent(
469
- appuser,
470
- this.documentName,
471
- result._id,
472
- 'create',
473
- data,
474
- );
400
+ await this.audittrail.addEvent(appuser, this.documentName, result._id, 'create', data);
475
401
  appuser.addInsertedRecordId(this.documentName, result._id);
476
402
  } catch (err) {
477
403
  this.logger.error(err);
478
- const processdata = await this.runWorker(
479
- appuser,
480
- 'processdata.processError',
481
- {
482
- err: err,
483
- },
484
- );
404
+ const processdata = await this.runWorker(appuser, 'processdata.processError', {
405
+ err: err,
406
+ });
485
407
 
486
408
  if (!processdata) {
487
409
  throw new InternalServerErrorException(err);
@@ -491,22 +413,16 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
491
413
  }
492
414
 
493
415
  try {
494
- if (this.hooks.afterCreate)
495
- await this.hooks.afterCreate(appuser, result);
416
+ if (this.hooks.afterCreate) await this.hooks.afterCreate(appuser, result);
496
417
  await this.callWebhook(appuser, 'create', result);
497
418
 
498
419
  // return result as T;
499
420
  } catch (err) {
500
- throw new InternalServerErrorException(
501
- `createHook ${this.documentType} error: ${JSON.stringify(err)}`,
502
- `${this.documentType} createHook error`,
503
- );
421
+ throw new InternalServerErrorException(`createHook ${this.documentType} error: ${JSON.stringify(err)}`, `${this.documentType} createHook error`);
504
422
  }
505
423
  }
506
424
  } else {
507
- throw new BadRequestException(
508
- this.getDocumentType() + ': create many only support array',
509
- );
425
+ throw new BadRequestException(this.getDocumentType() + ': create many only support array');
510
426
  }
511
427
  return 'ok';
512
428
  }
@@ -530,17 +446,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
530
446
  }
531
447
 
532
448
  const result = await this.doc.insertMany(datas);
533
- await this.audittrail.addManyEvents(
534
- appuser,
535
- this.documentName,
536
- 'createMany',
537
- datas,
538
- );
449
+ await this.audittrail.addManyEvents(appuser, this.documentName, 'createMany', datas);
539
450
  return result;
540
451
  } else {
541
- throw new BadRequestException(
542
- this.getDocumentType() + ': create many only support array',
543
- );
452
+ throw new BadRequestException(this.getDocumentType() + ': create many only support array');
544
453
  }
545
454
  }
546
455
  async createWithId(appuser: UserContext, data: T) {
@@ -551,16 +460,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
551
460
  }
552
461
  const dbsession = appuser.getDBSession();
553
462
  if (dbsession && !dbsession.inTransaction()) {
554
- dbsession.startTransaction();
463
+ dbsession.startTransaction({ readPreference: 'primary' });
555
464
  }
556
465
 
557
- this.logger.debug(
558
- 'this.withDocNumberFormat :' +
559
- this.withDocNumberFormat +
560
- ' && ' +
561
- '!data[this.documentIdentityCode] ==' +
562
- !data[this.documentIdentityCode],
563
- );
466
+ this.logger.debug('this.withDocNumberFormat :' + this.withDocNumberFormat + ' && ' + '!data[this.documentIdentityCode] ==' + !data[this.documentIdentityCode]);
564
467
  if (this.withDocNumberFormat && !data[this.documentIdentityCode]) {
565
468
  await this.genNewDocNo(appuser, data);
566
469
  }
@@ -584,23 +487,13 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
584
487
  await this.identifyForeignKeys(appuser, data);
585
488
  try {
586
489
  result = await newdoc.save({ session: dbsession });
587
- await this.audittrail.addEvent(
588
- appuser,
589
- this.documentName,
590
- result._id,
591
- 'create',
592
- data,
593
- );
490
+ await this.audittrail.addEvent(appuser, this.documentName, result._id, 'create', data);
594
491
  appuser.addInsertedRecordId(this.documentName, result._id);
595
492
  } catch (err) {
596
493
  this.logger.error(err);
597
- const processdata = await this.runWorker(
598
- appuser,
599
- 'processdata.processError',
600
- {
601
- err: err,
602
- },
603
- );
494
+ const processdata = await this.runWorker(appuser, 'processdata.processError', {
495
+ err: err,
496
+ });
604
497
 
605
498
  if (!processdata) {
606
499
  throw new InternalServerErrorException(err);
@@ -614,18 +507,11 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
614
507
  await this.callWebhook(appuser, 'create', result);
615
508
  return result as T;
616
509
  } catch (err) {
617
- throw new InternalServerErrorException(
618
- `createHook ${this.documentType} error: ${JSON.stringify(err)}`,
619
- `${this.documentType} createHook error`,
620
- );
510
+ throw new InternalServerErrorException(`createHook ${this.documentType} error: ${JSON.stringify(err)}`, `${this.documentType} createHook error`);
621
511
  }
622
512
  }
623
513
 
624
- async create(
625
- appuser: UserContext,
626
- data: T,
627
- noStartTransaction: boolean = false,
628
- ) {
514
+ async create(appuser: UserContext, data: T, noStartTransaction: boolean = false) {
629
515
  let result;
630
516
 
631
517
  if (!data._id) {
@@ -633,16 +519,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
633
519
  }
634
520
  const dbsession = appuser.getDBSession();
635
521
  if (dbsession && !dbsession.inTransaction() && !noStartTransaction) {
636
- dbsession.startTransaction();
522
+ dbsession.startTransaction({ readPreference: 'primary' });
637
523
  }
638
524
 
639
- this.logger.debug(
640
- 'this.withDocNumberFormat :' +
641
- this.withDocNumberFormat +
642
- ' && ' +
643
- '!data[this.documentIdentityCode] ==' +
644
- !data[this.documentIdentityCode],
645
- );
525
+ this.logger.debug('this.withDocNumberFormat :' + this.withDocNumberFormat + ' && ' + '!data[this.documentIdentityCode] ==' + !data[this.documentIdentityCode]);
646
526
  if (this.withDocNumberFormat && !data[this.documentIdentityCode]) {
647
527
  await this.genNewDocNo(appuser, data);
648
528
  }
@@ -666,23 +546,13 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
666
546
  await this.identifyForeignKeys(appuser, data);
667
547
  try {
668
548
  result = await newdoc.save({ session: dbsession });
669
- await this.audittrail.addEvent(
670
- appuser,
671
- this.documentName,
672
- result._id,
673
- 'create',
674
- data,
675
- );
549
+ await this.audittrail.addEvent(appuser, this.documentName, result._id, 'create', data);
676
550
  appuser.addInsertedRecordId(this.documentName, result._id);
677
551
  } catch (err) {
678
552
  this.logger.error(err);
679
- const processdata = await this.runWorker(
680
- appuser,
681
- 'processdata.processError',
682
- {
683
- err: err,
684
- },
685
- );
553
+ const processdata = await this.runWorker(appuser, 'processdata.processError', {
554
+ err: err,
555
+ });
686
556
 
687
557
  if (!processdata) {
688
558
  throw new InternalServerErrorException(err);
@@ -696,40 +566,23 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
696
566
  await this.callWebhook(appuser, 'create', result);
697
567
  return result as T;
698
568
  } catch (err) {
699
- throw new InternalServerErrorException(
700
- `createHook ${this.documentType} error: ${JSON.stringify(err)}`,
701
- `${this.documentType} createHook error`,
702
- );
569
+ throw new InternalServerErrorException(`createHook ${this.documentType} error: ${JSON.stringify(err)}`, `${this.documentType} createHook error`);
703
570
  }
704
571
  }
705
572
 
706
- applyNestedDateTime = (
707
- appuser: UserContext,
708
- data: any,
709
- transtype: string,
710
- ) => {
573
+ applyNestedDateTime = (appuser: UserContext, data: any, transtype: string) => {
711
574
  const props = Object.getOwnPropertyNames(data);
712
575
  for (let i = 0; i < props.length; i++) {
713
576
  const key = props[i];
714
577
  //need to apply nested
715
- if (
716
- Array.isArray(data[key]) &&
717
- data[key].length > 0 &&
718
- typeof data[key][0] == 'object'
719
- ) {
578
+ if (Array.isArray(data[key]) && data[key].length > 0 && typeof data[key][0] == 'object') {
720
579
  for (let j = 0; j < data[key].length; j++) {
721
580
  this.applyNestedDateTime(appuser, data[key][j], transtype);
722
581
  }
723
582
  } else if (key == 'created') {
724
- data['created'] =
725
- transtype == 'create' || !data['created']
726
- ? new Date().toISOString()
727
- : data['created'];
583
+ data['created'] = transtype == 'create' || !data['created'] ? new Date().toISOString() : data['created'];
728
584
  } else if (key == 'createdBy') {
729
- data['createdBy'] =
730
- transtype == 'create' || !data['createdBy']
731
- ? appuser.getUid()
732
- : data['createdBy'];
585
+ data['createdBy'] = transtype == 'create' || !data['createdBy'] ? appuser.getUid() : data['createdBy'];
733
586
  } else if (key == 'updated') {
734
587
  data['updated'] = new Date().toISOString();
735
588
  } else if (key == 'updatedBy') {
@@ -764,10 +617,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
764
617
  errormsg.push(this.errorlist[i].message);
765
618
  }
766
619
 
767
- throw new BadRequestException(
768
- 'Before validation hook failed',
769
- errormsg as HttpExceptionOptions,
770
- );
620
+ throw new BadRequestException('Before validation hook failed', errormsg as HttpExceptionOptions);
771
621
  }
772
622
 
773
623
  let validate;
@@ -781,14 +631,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
781
631
  if (!valid) {
782
632
  this.logger.error(JSON.stringify(data));
783
633
  this.logger.error(JSON.stringify(validate.errors), 'validate errors:');
784
- throw new BadRequestException(
785
- 'Data validation failed',
786
- validate.errors as HttpExceptionOptions,
787
- );
634
+ throw new BadRequestException('Data validation failed', validate.errors as HttpExceptionOptions);
788
635
  }
789
636
  //no check for duplicate those
790
- if (this.hooks.afterValidation)
791
- await this.hooks.afterValidation(appuser, data, _id);
637
+ if (this.hooks.afterValidation) await this.hooks.afterValidation(appuser, data, _id);
792
638
  }
793
639
 
794
640
  polishIsolationFilter = (filterIsolation: any, data: any = {}) => {
@@ -825,13 +671,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
825
671
  }
826
672
  const dbsession = appuser.getDBSession();
827
673
  if (dbsession && !dbsession.inTransaction()) {
828
- dbsession.startTransaction();
674
+ dbsession.startTransaction({ readPreference: 'primary' });
829
675
  }
830
676
 
831
677
  let dependency;
832
678
  try {
833
- if (this.hooks.beforeDelete)
834
- await this.hooks.beforeDelete(appuser, id, deletedata);
679
+ if (this.hooks.beforeDelete) await this.hooks.beforeDelete(appuser, id, deletedata);
835
680
  this.logger.debug('delete record', this.documentName, id);
836
681
  dependency = await this.getRelatedRecords(appuser, id);
837
682
  //console.log('dependency', dependency);
@@ -841,40 +686,25 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
841
686
 
842
687
  filterIsolation['_id'] = id;
843
688
  this.logger.debug('delete filter', filterIsolation);
844
- const result = await this.doc
845
- .deleteOne(filterIsolation)
846
- .session(dbsession);
847
- await this.audittrail.addEvent(
848
- appuser,
849
- this.documentName,
850
- id,
851
- 'delete',
852
- deletedata,
853
- );
689
+ const result = await this.doc.deleteOne(filterIsolation).session(dbsession);
690
+ await this.audittrail.addEvent(appuser, this.documentName, id, 'delete', deletedata);
854
691
 
855
692
  appuser.addDeletedRecordId(this.documentName, id);
856
693
  const deleteresult: DeleteResultType<T> = {
857
694
  result: result,
858
695
  data: deletedata,
859
696
  };
860
- this.logger.debug(
861
- deleteresult,
862
- ' delete result' + this.doc.collection.name,
863
- );
697
+ this.logger.debug(deleteresult, ' delete result' + this.doc.collection.name);
864
698
  // this.doc.findByIdAndDelete(id)
865
699
 
866
- if (this.hooks.afterDelete)
867
- await this.hooks.afterDelete(appuser, deleteresult, id);
700
+ if (this.hooks.afterDelete) await this.hooks.afterDelete(appuser, deleteresult, id);
868
701
  //this.doc.findByIdAndDelete(id);
869
702
  await this.callWebhook(appuser, 'delete', deletedata);
870
703
  return deleteresult;
871
704
  } else {
872
705
  this.logger.debug('reject query', dependency);
873
706
 
874
- throw new ForbiddenException(
875
- `This system detected that the [${this.documentName}] data has been used in other record`,
876
- 'Foreignkey constraint',
877
- );
707
+ throw new ForbiddenException(`This system detected that the [${this.documentName}] data has been used in other record`, 'Foreignkey constraint');
878
708
  }
879
709
  } catch (err) {
880
710
  if (err instanceof ForbiddenException) {
@@ -889,29 +719,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
889
719
  // this.doc.updateOne(data);
890
720
  // };
891
721
 
892
- findIdThenUpdate = async (
893
- appuser: UserContext,
894
- id: string,
895
- data: T,
896
- noStartTransaction: boolean = false,
897
- ) => {
722
+ findIdThenUpdate = async (appuser: UserContext, id: string, data: T, noStartTransaction: boolean = false) => {
898
723
  try {
899
724
  //version exists, need ensure different only 1
900
725
  const existingdata = await this.findById(appuser, id);
901
- if (!existingdata)
902
- throw new NotFoundException(
903
- `${this.documentName} findIdThenUpdate: _id:${id} not found`,
904
- 'not found',
905
- );
906
-
907
- this.logger.debug(
908
- 'update id:' + id,
909
- this.documentName + ' findIdThenUpdate',
910
- );
726
+ if (!existingdata) throw new NotFoundException(`${this.documentName} findIdThenUpdate: _id:${id} not found`, 'not found');
727
+
728
+ this.logger.debug('update id:' + id, this.documentName + ' findIdThenUpdate');
911
729
  if (typeof data.__v == 'number' && data.__v != existingdata.__v) {
912
- throw new BadRequestException(
913
- `You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`,
914
- );
730
+ throw new BadRequestException(`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`);
915
731
  }
916
732
  // this.logger.debug('warn1', existingdata);
917
733
  data.__v = existingdata.__v + 1;
@@ -919,15 +735,14 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
919
735
  // throw new NotFoundException(`${id} not found`, 'not found');
920
736
  // }
921
737
  // this.logger.debug('warn2');
922
-
738
+
923
739
  await this.identifyForeignKeys(appuser, data);
924
740
 
925
- if (this.hooks.beforeUpdate)
926
- await this.hooks.beforeUpdate(appuser, id, existingdata, data);
741
+ if (this.hooks.beforeUpdate) await this.hooks.beforeUpdate(appuser, id, existingdata, data);
927
742
 
928
743
  const dbsession = appuser.getDBSession();
929
744
  if (dbsession && !dbsession.inTransaction() && !noStartTransaction) {
930
- dbsession.startTransaction();
745
+ dbsession.startTransaction({ readPreference: 'primary' });
931
746
  }
932
747
  // try {
933
748
  Object.assign(data, appuser.getUpdateFilter());
@@ -948,17 +763,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
948
763
  session: dbsession,
949
764
  new: true,
950
765
  });
951
- await this.audittrail.addEvent(
952
- appuser,
953
- this.documentName,
954
- id,
955
- 'update',
956
- data,
957
- );
766
+ await this.audittrail.addEvent(appuser, this.documentName, id, 'update', data);
958
767
 
959
768
  appuser.addUpdatedRecordId(this.documentName, data._id);
960
- if (this.hooks.afterUpdate)
961
- await this.hooks.afterUpdate(appuser, id, existingdata, result);
769
+ if (this.hooks.afterUpdate) await this.hooks.afterUpdate(appuser, id, existingdata, result);
962
770
  await this.callWebhook(appuser, 'update', result);
963
771
  return result; // await this.findById(appuser, id);
964
772
  } catch (err) {
@@ -967,28 +775,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
967
775
  }
968
776
  };
969
777
 
970
- findIdThenUpdateNoIsolation = async (
971
- appuser: UserContext,
972
- id: string,
973
- data: T,
974
- ) => {
778
+ findIdThenUpdateNoIsolation = async (appuser: UserContext, id: string, data: T) => {
975
779
  try {
976
780
  //version exists, need ensure different only 1
977
781
  const existingdata = await this.findByIdNoIsolation(appuser, id);
978
- if (!existingdata)
979
- throw new NotFoundException(
980
- `${this.documentName} findIdThenUpdate: _id:${id} not found`,
981
- 'not found',
982
- );
983
-
984
- this.logger.debug(
985
- 'update id:' + id,
986
- this.documentName + ' findIdThenUpdate',
987
- );
782
+ if (!existingdata) throw new NotFoundException(`${this.documentName} findIdThenUpdate: _id:${id} not found`, 'not found');
783
+
784
+ this.logger.debug('update id:' + id, this.documentName + ' findIdThenUpdate');
988
785
  if (typeof data.__v == 'number' && data.__v != existingdata.__v) {
989
- throw new BadRequestException(
990
- `You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`,
991
- );
786
+ throw new BadRequestException(`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`);
992
787
  }
993
788
  // this.logger.debug('warn1', existingdata);
994
789
  data.__v = existingdata.__v + 1;
@@ -996,15 +791,14 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
996
791
  // throw new NotFoundException(`${id} not found`, 'not found');
997
792
  // }
998
793
  // this.logger.debug('warn2');
999
-
794
+
1000
795
  await this.identifyForeignKeys(appuser, data);
1001
796
 
1002
- if (this.hooks.beforeUpdate)
1003
- await this.hooks.beforeUpdate(appuser, id, existingdata, data);
797
+ if (this.hooks.beforeUpdate) await this.hooks.beforeUpdate(appuser, id, existingdata, data);
1004
798
 
1005
799
  const dbsession = appuser.getDBSession();
1006
800
  if (dbsession && !dbsession.inTransaction()) {
1007
- dbsession.startTransaction();
801
+ dbsession.startTransaction({ readPreference: 'primary' });
1008
802
  }
1009
803
  // try {
1010
804
  // Object.assign(data, appuser.getUpdateFilter());
@@ -1025,17 +819,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1025
819
  session: dbsession,
1026
820
  new: true,
1027
821
  });
1028
- await this.audittrail.addEvent(
1029
- appuser,
1030
- this.documentName,
1031
- id,
1032
- 'update',
1033
- data,
1034
- );
822
+ await this.audittrail.addEvent(appuser, this.documentName, id, 'update', data);
1035
823
 
1036
824
  appuser.addUpdatedRecordId(this.documentName, data._id);
1037
- if (this.hooks.afterUpdate)
1038
- await this.hooks.afterUpdate(appuser, id, existingdata, result);
825
+ if (this.hooks.afterUpdate) await this.hooks.afterUpdate(appuser, id, existingdata, result);
1039
826
  await this.callWebhook(appuser, 'update', result);
1040
827
  return result; // await this.findById(appuser, id);
1041
828
  } catch (err) {
@@ -1044,32 +831,24 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1044
831
  }
1045
832
  };
1046
833
 
1047
- findIdThenPatch = async (
1048
- appuser: UserContext,
1049
- id: string,
1050
- data: T,
1051
- session: mongo.ClientSession = undefined,
1052
- ) => {
834
+ findIdThenPatch = async (appuser: UserContext, id: string, data: T, session: mongo.ClientSession = undefined) => {
1053
835
  const existingdata = await this.findById(appuser, id);
1054
836
  if (!existingdata) {
1055
837
  throw new NotFoundException(`${id} not found`, 'not found');
1056
838
  }
1057
839
  if (typeof data.__v == 'number' && data.__v != existingdata.__v) {
1058
- throw new BadRequestException(
1059
- `You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`,
1060
- );
840
+ throw new BadRequestException(`You submit older version data "v${data.__v}"" but latest version = "v${existingdata.__v}"`);
1061
841
  }
1062
842
 
1063
843
  data.__v = existingdata.__v + 1;
1064
-
844
+
1065
845
  await this.identifyForeignKeys(appuser, data);
1066
846
 
1067
- if (this.hooks.beforeUpdate)
1068
- await this.hooks.beforeUpdate(appuser, id, existingdata, data);
847
+ if (this.hooks.beforeUpdate) await this.hooks.beforeUpdate(appuser, id, existingdata, data);
1069
848
 
1070
849
  const dbsession = appuser.getDBSession();
1071
850
  if (dbsession && !dbsession.inTransaction()) {
1072
- dbsession.startTransaction();
851
+ dbsession.startTransaction({ readPreference: 'primary' });
1073
852
  }
1074
853
  // try {
1075
854
  Object.assign(data, appuser.getUpdateFilter());
@@ -1094,17 +873,10 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1094
873
  session: dbsession,
1095
874
  new: true,
1096
875
  });
1097
- await this.audittrail.addEvent(
1098
- appuser,
1099
- this.documentName,
1100
- id,
1101
- 'patch',
1102
- data,
1103
- );
876
+ await this.audittrail.addEvent(appuser, this.documentName, id, 'patch', data);
1104
877
  appuser.addUpdatedRecordId(this.documentName, data._id);
1105
878
 
1106
- if (this.hooks.afterUpdate)
1107
- await this.hooks.afterUpdate(appuser, id, existingdata, result);
879
+ if (this.hooks.afterUpdate) await this.hooks.afterUpdate(appuser, id, existingdata, result);
1108
880
  await this.callWebhook(appuser, 'update', result);
1109
881
  return result; //await this.findById(appuser, id);
1110
882
  } catch (err) {
@@ -1144,10 +916,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1144
916
  session: appuser.getDBSession(),
1145
917
  });
1146
918
  if (result) {
1147
- this.logger.error(
1148
- result,
1149
- `related result found in ${collectionname} ${fkey} = ${id}`,
1150
- );
919
+ this.logger.error(result, `related result found in ${collectionname} ${fkey} = ${id}`);
1151
920
  return result;
1152
921
  }
1153
922
  }
@@ -1170,62 +939,34 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1170
939
  * @param docstatus
1171
940
  * @returns Promise
1172
941
  */
1173
- async setDocumentStatus(
1174
- appuser: UserContext,
1175
- id: string,
1176
- data: T,
1177
- docstatus: string,
1178
- ) {
942
+ async setDocumentStatus(appuser: UserContext, id: string, data: T, docstatus: string) {
1179
943
  id = id.trim();
1180
944
 
1181
945
  if (!id) {
1182
- throw new BadRequestException(
1183
- 'undefined path para "id"',
1184
- 'undefined "id"',
1185
- );
946
+ throw new BadRequestException('undefined path para "id"', 'undefined "id"');
1186
947
  }
1187
948
  if (data['_id'] && data['_id'] != id) {
1188
- throw new BadRequestException(
1189
- `_id in data(${data['_id']} different with path param ${id})`,
1190
- 'set documentstatus id not match with submited data',
1191
- );
949
+ throw new BadRequestException(`_id in data(${data['_id']} different with path param ${id})`, 'set documentstatus id not match with submited data');
1192
950
  }
1193
951
  const existdata = await this.findById(appuser, id);
1194
952
  if (existdata && existdata['documentStatus'] == docstatus) {
1195
- throw new BadRequestException(
1196
- `Same document status "${docstatus}" is not allowed`,
1197
- );
953
+ throw new BadRequestException(`Same document status "${docstatus}" is not allowed`);
1198
954
  }
1199
955
  data['documentStatus'] = docstatus;
1200
956
  // await this.hook(appuser, HookType.beforeSetStatus, data);
1201
- if (this.hooks.beforeSetStatus)
1202
- await this.hooks.beforeSetStatus(appuser, docstatus, data, existdata);
957
+ if (this.hooks.beforeSetStatus) await this.hooks.beforeSetStatus(appuser, docstatus, data, existdata);
1203
958
 
1204
959
  if (data && !data['created']) {
1205
960
  const createresult = await this.create(appuser, data);
1206
- if (this.hooks.afterSetStatus)
1207
- await this.hooks.afterSetStatus(appuser, docstatus, createresult);
1208
- await this.audittrail.addEvent(
1209
- appuser,
1210
- this.documentName,
1211
- id,
1212
- docstatus,
1213
- data,
1214
- );
961
+ if (this.hooks.afterSetStatus) await this.hooks.afterSetStatus(appuser, docstatus, createresult);
962
+ await this.audittrail.addEvent(appuser, this.documentName, id, docstatus, data);
1215
963
 
1216
964
  return createresult;
1217
965
  } else {
1218
966
  const updateresult = await this.findIdThenPatch(appuser, id, data);
1219
967
  const finaldata = await this.findById(appuser, id);
1220
- if (this.hooks.afterSetStatus)
1221
- await this.hooks.afterSetStatus(appuser, docstatus, finaldata);
1222
- await this.audittrail.addEvent(
1223
- appuser,
1224
- this.documentName,
1225
- id,
1226
- docstatus,
1227
- data,
1228
- );
968
+ if (this.hooks.afterSetStatus) await this.hooks.afterSetStatus(appuser, docstatus, finaldata);
969
+ await this.audittrail.addEvent(appuser, this.documentName, id, docstatus, data);
1229
970
 
1230
971
  await this.callWebhook(appuser, docstatus, finaldata);
1231
972
  return updateresult;
@@ -1274,33 +1015,18 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1274
1015
  if (result?.name && result?.name.includes('Exception')) throw result;
1275
1016
  return result;
1276
1017
  }
1277
- startWorkflow(
1278
- appuser: UserContext,
1279
- processName: WorkflowName,
1280
- workflowData: any,
1281
- ) {
1282
- return this.eventEmitter.emit(
1283
- 'workflow.start',
1284
- appuser,
1285
- processName,
1286
- workflowData,
1287
- );
1018
+ startWorkflow(appuser: UserContext, processName: WorkflowName, workflowData: any) {
1019
+ return this.eventEmitter.emit('workflow.start', appuser, processName, workflowData);
1288
1020
  }
1289
1021
 
1290
1022
  async genNewDocNo(appuser: UserContext, data: T) {
1291
1023
  this.logger.debug('genNewDocNo');
1292
- const result = await this.docnogenerator.generateNextNumberFromDocument(
1293
- appuser,
1294
- this.documentType,
1295
- data,
1296
- );
1024
+ const result = await this.docnogenerator.generateNextNumberFromDocument(appuser, this.documentType, data);
1297
1025
  this.logger.debug(result, 'genNewDocNo');
1298
1026
  data[this.documentIdentityCode] = result;
1299
1027
  }
1300
1028
  async runDefault(appuser: UserContext): Promise<unknown> {
1301
- return (
1302
- 'Hello this is ' + this.getDocumentType() + ': ' + this.getDocumentName()
1303
- );
1029
+ return 'Hello this is ' + this.getDocumentType() + ': ' + this.getDocumentName();
1304
1030
  }
1305
1031
  async identifyForeignKeys(appuser: UserContext, data: T) {
1306
1032
  /**
@@ -1322,9 +1048,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1322
1048
  let results: string[] = [];
1323
1049
  fks.forEach((fieldpath) => {
1324
1050
  //console.log("fieldpath:",fieldpath,"vdata",data,vdata)
1325
- const tmp = jsonpath
1326
- .query(vdata, fieldpath)
1327
- .filter((item: string) => item != '');
1051
+ const tmp = jsonpath.query(vdata, fieldpath).filter((item: string) => item != '');
1328
1052
  // console.log("tmp",tmp)
1329
1053
 
1330
1054
  results = results.concat(tmp);
@@ -1342,11 +1066,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1342
1066
  const stagefilter: PipelineStage = {
1343
1067
  $unionWith: {
1344
1068
  coll: collectionname,
1345
- pipeline: [
1346
- { $match: { _id: { $in: results } } },
1347
- addfield,
1348
- { $project: { collection: 1 } },
1349
- ],
1069
+ pipeline: [{ $match: { _id: { $in: results } } }, addfield, { $project: { collection: 1 } }],
1350
1070
  },
1351
1071
  };
1352
1072
  pipelines.push(stagefilter);
@@ -1358,10 +1078,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1358
1078
 
1359
1079
  if (!unionresult) {
1360
1080
  this.logger.error('foreign key control failed ', 'identifyForeignKeys');
1361
- throw new InternalServerErrorException(
1362
- 'Foreignkey check execution error',
1363
- pipelines as HttpExceptionOptions,
1364
- );
1081
+ throw new InternalServerErrorException('Foreignkey check execution error', pipelines as HttpExceptionOptions);
1365
1082
  } else {
1366
1083
  const searchresult: any = {};
1367
1084
  unionresult.forEach((item) => {
@@ -1382,26 +1099,15 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1382
1099
  }
1383
1100
  for (let k = 0; k < keys.length; k++) {
1384
1101
  const key = keys[k];
1385
- if (
1386
- searchresult[collectionname] &&
1387
- searchresult[collectionname].includes(key)
1388
- ) {
1102
+ if (searchresult[collectionname] && searchresult[collectionname].includes(key)) {
1389
1103
  this.logger.debug(`foreignkey ${collectionname}->${key} exists`);
1390
1104
  } else if (appuser.searchInsertedRecordId(collectionname, key)) {
1391
- this.logger.debug(
1392
- `foreignkey ${collectionname} exists in user context which not yet commited`,
1393
- );
1105
+ this.logger.debug(`foreignkey ${collectionname} exists in user context which not yet commited`);
1394
1106
  } else {
1395
- this.logger.warn(
1396
- `${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`,
1397
- 'identifyForeignKeys',
1398
- );
1107
+ this.logger.warn(`${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`, 'identifyForeignKeys');
1399
1108
  this.logger.debug(appuser.getModifieds, 'appuser.getModifieds');
1400
1109
  const errordata = { key: key, collection: collectionname };
1401
- throw new BadRequestException(
1402
- `${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`,
1403
- JSON.stringify(errordata),
1404
- );
1110
+ throw new BadRequestException(`${this.documentType}: Foreignkey ${key} at collection ${collectionname} does not exist`, JSON.stringify(errordata));
1405
1111
  }
1406
1112
  }
1407
1113
  }
@@ -1413,10 +1119,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1413
1119
  return pdfresult;
1414
1120
  }
1415
1121
 
1416
- async checkMultipleUnionExist(
1417
- appuser: UserContext,
1418
- data: string[],
1419
- ): Promise<CheckMutipleUnionExistResponse> {
1122
+ async checkMultipleUnionExist(appuser: UserContext, data: string[]): Promise<CheckMutipleUnionExistResponse> {
1420
1123
  const response: CheckMutipleUnionExistResponse = [];
1421
1124
  const unionKey = this.getDocumentIdentityCode();
1422
1125
  const searchQuery: any = { [unionKey]: { $in: data } };
@@ -1430,13 +1133,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1430
1133
  return response;
1431
1134
  }
1432
1135
 
1433
- searchToAggregate(
1434
- appuser: UserContext,
1435
- filter: FilterQuery<T>,
1436
- columns: string[],
1437
- sort: string[][],
1438
- lookup: { [key: string]: string },
1439
- ) {
1136
+ searchToAggregate(appuser: UserContext, filter: FilterQuery<T>, columns: string[], sort: string[][], lookup: { [key: string]: string }) {
1440
1137
  const pipelines: PipelineStage[] = [];
1441
1138
  const projection = {};
1442
1139
  // console.log('sortsort', sort);
@@ -1470,8 +1167,7 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1470
1167
  if (Object.keys(projection).length > 0) projection['_' + to] = 1;
1471
1168
  });
1472
1169
 
1473
- if (Object.keys(projection).length > 0)
1474
- pipelines.push({ $project: projection });
1170
+ if (Object.keys(projection).length > 0) pipelines.push({ $project: projection });
1475
1171
 
1476
1172
  if (Array.isArray(sort) && sort.length > 0) {
1477
1173
  const sortobj = {};
@@ -1485,16 +1181,12 @@ export class SimpleAppService<T extends { _id?: string; __v?: number }> {
1485
1181
  return pipelines;
1486
1182
  }
1487
1183
 
1488
-
1489
1184
  //only realtime webhook supported at this moment
1490
1185
  async callWebhook(appuser: UserContext, actionName: string, data: any) {
1491
- try{
1492
- await this.runWebHook.run(appuser,this.documentName, actionName,data)
1493
- }
1494
- catch(e)
1495
- {
1186
+ try {
1187
+ await this.runWebHook.run(appuser, this.documentName, actionName, data);
1188
+ } catch (e) {
1496
1189
  throw new InternalServerErrorException(e);
1497
1190
  }
1498
-
1499
1191
  }
1500
1192
  }