@futdevpro/nts-dynamo 1.5.81 → 1.5.84

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.
@@ -6,10 +6,194 @@ import {
6
6
  Dynamo_Metadata, Dynamo_DataParams, Dynamo_DataPropertyParams, Dynamo_Error
7
7
  } from '@futdevpro/fsm-dynamo';
8
8
 
9
+ /**
10
+ * @example
11
+ * // by email:
12
+ * { email: email }
13
+ * //
14
+ * @example
15
+ * // or by id that is in list:
16
+ * { userIds: { $in: this.userId } }
17
+ * //
18
+ * @example
19
+ * // or by number or Date that is Greater Than AND Less Than:
20
+ * { points: { $gt: 2, $lt: 14 } }
21
+ * // further tools (syntax matches with $gt):
22
+ * $eq: // Matches values that are EQual to a specified value.
23
+ * $gte: // Matches values that are Greater Than OR Equal to a specified value.
24
+ * $lte: // Matches values that are Less Than or Equal to a specified value.
25
+ * $ne: // Matches all values that are Not Equal to a specified value.
26
+ * $nin: // Matches None of the values specified IN an array.
27
+ * //
28
+ * @returns {T} data: T
29
+ */
30
+ export type DynamoNTS_DBFilter<T> = DynamoNTS_DBFilterSimple<T> | DynamoNTS_DBFilterOR<T> |DynamoNTS_DBFilterNOR<T>;
31
+
32
+ type DynamoNTS_DBFilterSimple<T> = {
33
+ [K in keyof T]?: T[K] | {
34
+ /**
35
+ * Matches values that are includes the value; This works only when T[K] is an array!
36
+ */
37
+ $in?: any,
38
+ /**
39
+ * Matches values that are EQual to a specified value.
40
+ */
41
+ $eq?: T[K],
42
+ /**
43
+ * Matches values that are Greater Than a specified value.
44
+ */
45
+ $gt?: number | Date,
46
+ /**
47
+ * Matches values that are Greater Than OR Equal to a specified value.
48
+ */
49
+ $gte?: number | Date,
50
+ /**
51
+ * Matches values that are Less Than a specified value.
52
+ */
53
+ $lt?: number | Date,
54
+ /**
55
+ * Matches values that are Less Than or Equal to a specified value.
56
+ */
57
+ $lte?: number | Date,
58
+ /**
59
+ * Matches all values that are Not Equal to a specified value.
60
+ */
61
+ $ne?: T[K],
62
+ /**
63
+ * Matches None of the values specified IN an array.
64
+ */
65
+ $nin?: T[K],
66
+ /**
67
+ * Inverts the effect of a query expression and returns documents that do not match the query expression.
68
+ */
69
+ $not?: T[K] | {
70
+ $regex?: RegExp | string,
71
+ },
72
+ /**
73
+ * Performs a regular expression on the field's value, and selects documents that match the regular expression.
74
+ */
75
+ $exists?: boolean,
76
+ /**
77
+ * Selects documents if a field is of the specified type.
78
+ */
79
+ $type?: string,
80
+ };
81
+ };
82
+
83
+ type DynamoNTS_DBFilterOR<T> = {
84
+ /**
85
+ * Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
86
+ */
87
+ $or: DynamoNTS_DBFilterSimple<T>[];
88
+ }
89
+
90
+ type DynamoNTS_DBFilterNOR<T> = {
91
+ /**
92
+ * Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
93
+ */
94
+ $nor: DynamoNTS_DBFilterSimple<T>[];
95
+ }
96
+
97
+ /**
98
+ * @param update this uses the basic Mongoose updateOne
99
+ * @example
100
+ * // increase a specific value (here by 15):
101
+ * { $inc: { popularity: 15 } }
102
+ * //
103
+ * @example
104
+ * // or add element to a list:
105
+ * { $push: { reactions: this.newReaction }
106
+ * // or add multiple elements to a list
107
+ * { $push: { schedule: {$each: [ monday, tuesday, wednesday ] } } }
108
+ * //
109
+ * @example
110
+ * // or all at once
111
+ * {
112
+ * $inc: { popularity: this.newVote.amount },
113
+ * emailVerified: true,
114
+ * $push: { reactions: this.newReaction }
115
+ * }
116
+ * // further tools (syntax matches with $inc):
117
+ * $currentDate: // Sets the value of a field to current date, either as a Date or a Timestamp.
118
+ * $min: // Only updates the field if the specified value is less than the existing field value.
119
+ * $max: // Only updates the field if the specified value is greater than the existing field value.
120
+ * $mul: // Multiplies the value of the field by the specified amount.
121
+ * $rename: // Renames a field.
122
+ * $unset: // Removes the specified field from a document. (set: "" to value)
123
+ * //
124
+ */
125
+ export type DynamoNTS_DBUpdate<T> = {
126
+ /**
127
+ * Sets the value of a field to current date, either as a Date or a Timestamp.
128
+ */
129
+ $currentDate?: { [K in keyof T]?: boolean };
130
+ /**
131
+ * Increments the value of the field by the specified amount.
132
+ */
133
+ $inc?: { [K in keyof T]?: number };
134
+ /**
135
+ * Only updates the field if the specified value is less than the existing field value.
136
+ */
137
+ $min?: { [K in keyof T]?: number };
138
+ /**
139
+ * Only updates the field if the specified value is greater than the existing field value.
140
+ */
141
+ $max?: { [K in keyof T]?: number };
142
+ /**
143
+ * Multiplies the value of the field by the specified amount.
144
+ */
145
+ $mul?: { [K in keyof T]?: number };
146
+ /**
147
+ * Renames a field.
148
+ */
149
+ $rename?: { [K in keyof T]?: string };
150
+ /**
151
+ * Removes the specified field from a document. (set: "" to value)
152
+ */
153
+ $unset?: { [K in keyof T]?: string };
154
+ /**
155
+ * Sets the value of a field in a document.
156
+ */
157
+ $set?: { [K in keyof T]?: string };
158
+ /**
159
+ * Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
160
+ */
161
+ $setOnInsert?: { [K in keyof T]?: T[K] };
162
+ /**
163
+ * Removes the first or last item of an array.
164
+ */
165
+
166
+ // array only operations
167
+ /**
168
+ * Removes the first or last item of an array.
169
+ */
170
+ $push?: { [K in keyof T]?: any | { $each?: T[K] } };
171
+ /**
172
+ * Removes the first or last item of an array.
173
+ */
174
+ $addToSet?: { [K in keyof T]?: any | { $each?: T[K] } };
175
+ /**
176
+ * Removes the first or last item of an array.
177
+ */
178
+ $pop?: { [K in keyof T]?: 1 | -1 };
179
+ /**
180
+ * Removes all array elements that match a specified query.
181
+ */
182
+ $pull?: { [K in keyof T]?: any | { $each?: T[K] } };
183
+ /**
184
+ * Removes all array elements that match a specified query.
185
+ */
186
+ $pullAll?: { [K in keyof T]?: any | { $each?: T[K] } };
187
+ } extends DynamoNTS_DBSimpleUpdate<T> ? DynamoNTS_DBSimpleUpdate<T> : never;
188
+
189
+ type DynamoNTS_DBSimpleUpdate<T> = {
190
+ [K in keyof T]?: T[K];
191
+ };
192
+
9
193
  /**
10
194
  *
11
195
  */
12
- export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U extends T = any> {
196
+ export class DynamoNTS_DBService<T extends Dynamo_Metadata> {
13
197
  dataModel = mongoose.model(this.dataParams.dbName, this.getSchema());
14
198
 
15
199
  private depDataName: string;
@@ -269,15 +453,89 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
269
453
  return dataList;
270
454
  }
271
455
 
456
+ /**
457
+ * returns all data from database,
458
+ * !!!: throws error if not found (errorCode on not found: NTS-DBS-GA1)
459
+ *
460
+ * @returns dataList
461
+ */
462
+ async getAll(): Promise<T[]> {
463
+ let dataList: T[] = await this.dataModel.find({})
464
+ .then(res => {
465
+ return res as T[] ?? [];
466
+ }).catch(error => {
467
+ throw new Dynamo_Error({
468
+ status: 417,
469
+ errorCode: 'NTS-DBS-GA0',
470
+ addECToUserMsg: true,
471
+ message: `get all ${this.dataParams.dbName} was unsuccessful (NTS DB)`,
472
+ userMessage: this.defaultErrorUserMsg,
473
+ error
474
+ });
475
+ });
476
+
477
+ if (0 < dataList.length && typeof dataList[0]._id === 'object') {
478
+ dataList.forEach((data: T) => {
479
+ data._id = `˙${data._id}`;
480
+ });
481
+ }
482
+
483
+ return dataList as T[];
484
+ }
485
+
486
+ /**
487
+ * deleted data by id
488
+ * @param id id
489
+ */
490
+ async deleteDataById(id: string): Promise<void> {
491
+ await this.dataModel.findByIdAndDelete(id).catch(error => {
492
+ throw new Dynamo_Error({
493
+ status: 417,
494
+ errorCode: 'NTS-DBS-DD0',
495
+ addECToUserMsg: true,
496
+ message: `delete ${this.dataParams.dbName} was unsuccessful (NTS DB)`,
497
+ userMessage: this.defaultErrorUserMsg,
498
+ error
499
+ });
500
+ });
501
+ }
502
+
503
+ /**
504
+ * deleted data by id
505
+ * @param dependencyId id
506
+ */
507
+ async deleteDataByDependencyId(dependencyId: string): Promise<void> {
508
+ if (!this.depDataName) {
509
+ throw new Dynamo_Error({
510
+ status: 501,
511
+ errorCode: 'NTS-DBS-DDD0',
512
+ addECToUserMsg: true,
513
+ message: `dependencyDataIdKey not setted up for this db-service (${this.dataParams.dbName}) (NTS DB)`,
514
+ userMessage: this.defaultErrorUserMsg
515
+ });
516
+ }
517
+
518
+ await this.dataModel.deleteMany({ [this.depDataName]: dependencyId }).catch(error => {
519
+ throw new Dynamo_Error({
520
+ status: 417,
521
+ errorCode: 'NTS-DBS-DDD1',
522
+ addECToUserMsg: true,
523
+ message: `delete ${this.dataParams.dbName} by ${this.depDataName} was unsuccessful (NTS DB)`,
524
+ userMessage: this.defaultErrorUserMsg,
525
+ error
526
+ });
527
+ });
528
+ }
529
+
272
530
  /**
273
531
  * returns search result for searchBy object params
274
532
  * can use lists or xRange values for searchBy obj properties
275
533
  *
276
- * @param searchBy filter
534
+ * @param filterBy filter
277
535
  * @param narrowByDependencyIds id
278
536
  * @returns dataList
279
537
  */
280
- async searchData(searchBy: F, narrowByDependencyIds?: string[]): Promise<T[]> {
538
+ async searchData(filterBy: DynamoNTS_DBFilter<T>, narrowByDependencyIds?: string[]): Promise<T[]> {
281
539
  const filter = {};
282
540
 
283
541
  if (0 < narrowByDependencyIds.length) {
@@ -296,45 +554,45 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
296
554
 
297
555
  await this.dataParams.modelParams.forEach((modelParam: Dynamo_DataPropertyParams) => {
298
556
  if (
299
- (searchBy[modelParam.key] !== null && searchBy[modelParam.key] !== undefined) ||
300
- searchBy[modelParam.key + 'Range']
557
+ (filterBy[modelParam.key] !== null && filterBy[modelParam.key] !== undefined) ||
558
+ filterBy[modelParam.key + 'Range']
301
559
  ) {
302
560
  if (modelParam.key.includes('Range') || modelParam.type.includes('[]')) {
303
561
  // inverz search filter (for Range and Array functions)
304
562
  if (modelParam.key.includes('Range')) {
305
563
  const searchParamKeyWithoutRange = modelParam.key.split('Range')[0];
306
564
  if (
307
- searchBy[searchParamKeyWithoutRange] !== null &&
308
- searchBy[searchParamKeyWithoutRange] !== undefined
565
+ filterBy[searchParamKeyWithoutRange] !== null &&
566
+ filterBy[searchParamKeyWithoutRange] !== undefined
309
567
  ) {
310
568
  filter[modelParam.key] = {
311
- from: { $lte: searchBy[searchParamKeyWithoutRange] },
312
- to: { $gte: searchBy[searchParamKeyWithoutRange] }
569
+ from: { $lte: filterBy[searchParamKeyWithoutRange] },
570
+ to: { $gte: filterBy[searchParamKeyWithoutRange] }
313
571
  };
314
572
  }
315
573
  } else {
316
574
  if (
317
- searchBy[modelParam.key] !== null &&
318
- searchBy[modelParam.key] !== undefined
575
+ filterBy[modelParam.key] !== null &&
576
+ filterBy[modelParam.key] !== undefined
319
577
  ) {
320
- filter[modelParam.key] = { $in: searchBy[modelParam.key] };
578
+ filter[modelParam.key] = { $in: filterBy[modelParam.key] };
321
579
  }
322
580
  }
323
581
  } else {
324
582
  // basic search filter
325
- if (searchBy[modelParam.key + 'Range']) {
326
- if (searchBy[modelParam.key + 'Range'].from || searchBy[modelParam.key + 'Range'].to) {
583
+ if (filterBy[modelParam.key + 'Range']) {
584
+ if (filterBy[modelParam.key + 'Range'].from || filterBy[modelParam.key + 'Range'].to) {
327
585
  filter[modelParam.key] = {};
328
- if (searchBy[modelParam.key + 'Range'].from) {
329
- filter[modelParam.key].$gte = searchBy[modelParam.key + 'Range'].from;
586
+ if (filterBy[modelParam.key + 'Range'].from) {
587
+ filter[modelParam.key].$gte = filterBy[modelParam.key + 'Range'].from;
330
588
  }
331
- if (searchBy[modelParam.key + 'Range'].to) {
332
- filter[modelParam.key].$lte = searchBy[modelParam.key + 'Range'].to;
589
+ if (filterBy[modelParam.key + 'Range'].to) {
590
+ filter[modelParam.key].$lte = filterBy[modelParam.key + 'Range'].to;
333
591
  }
334
592
  }
335
- } else if (searchBy[modelParam.key] !== null && searchBy[modelParam.key] !== undefined) {
336
- if (searchBy[modelParam.key].lenght > 0) {
337
- filter[modelParam.key] = { $in: searchBy[modelParam.key] };
593
+ } else if (filterBy[modelParam.key] !== null && filterBy[modelParam.key] !== undefined) {
594
+ if (filterBy[modelParam.key].lenght > 0) {
595
+ filter[modelParam.key] = { $in: filterBy[modelParam.key] };
338
596
  }
339
597
  }
340
598
  }
@@ -365,80 +623,6 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
365
623
  return dataList;
366
624
  }
367
625
 
368
- /**
369
- * returns all data from database,
370
- * !!!: throws error if not found (errorCode on not found: NTS-DBS-GA1)
371
- *
372
- * @returns dataList
373
- */
374
- async getAll(): Promise<T[]> {
375
- let dataList: T[] = await this.dataModel.find({})
376
- .then(res => {
377
- return res as T[] ?? [];
378
- }).catch(error => {
379
- throw new Dynamo_Error({
380
- status: 417,
381
- errorCode: 'NTS-DBS-GA0',
382
- addECToUserMsg: true,
383
- message: `get all ${this.dataParams.dbName} was unsuccessful (NTS DB)`,
384
- userMessage: this.defaultErrorUserMsg,
385
- error
386
- });
387
- });
388
-
389
- if (0 < dataList.length && typeof dataList[0]._id === 'object') {
390
- dataList.forEach((data: T) => {
391
- data._id = `˙${data._id}`;
392
- });
393
- }
394
-
395
- return dataList as T[];
396
- }
397
-
398
- /**
399
- * deleted data by id
400
- * @param id id
401
- */
402
- async deleteDataById(id: string): Promise<void> {
403
- await this.dataModel.findByIdAndDelete(id).catch(error => {
404
- throw new Dynamo_Error({
405
- status: 417,
406
- errorCode: 'NTS-DBS-DD0',
407
- addECToUserMsg: true,
408
- message: `delete ${this.dataParams.dbName} was unsuccessful (NTS DB)`,
409
- userMessage: this.defaultErrorUserMsg,
410
- error
411
- });
412
- });
413
- }
414
-
415
- /**
416
- * deleted data by id
417
- * @param dependencyId id
418
- */
419
- async deleteDataByDependencyId(dependencyId: string): Promise<void> {
420
- if (!this.depDataName) {
421
- throw new Dynamo_Error({
422
- status: 501,
423
- errorCode: 'NTS-DBS-DDD0',
424
- addECToUserMsg: true,
425
- message: `dependencyDataIdKey not setted up for this db-service (${this.dataParams.dbName}) (NTS DB)`,
426
- userMessage: this.defaultErrorUserMsg
427
- });
428
- }
429
-
430
- await this.dataModel.deleteMany({ [this.depDataName]: dependencyId }).catch(error => {
431
- throw new Dynamo_Error({
432
- status: 417,
433
- errorCode: 'NTS-DBS-DDD1',
434
- addECToUserMsg: true,
435
- message: `delete ${this.dataParams.dbName} by ${this.depDataName} was unsuccessful (NTS DB)`,
436
- userMessage: this.defaultErrorUserMsg,
437
- error
438
- });
439
- });
440
- }
441
-
442
626
  // ----------------------------------------------------------------------------------
443
627
  // ----------------------------------------------------------------------------------
444
628
  // ----------------------------------------------------------------------------------
@@ -448,7 +632,7 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
448
632
  * Find the data first by any of its parameters,
449
633
  * !!!: throws error if not found (errorCode on not found: NTS-DBS-FO1)
450
634
  *
451
- * @param filter if you can, use unique parameters for find!
635
+ * @param filterBy if you can, use unique parameters for find!
452
636
  *
453
637
  * @example
454
638
  * // by email:
@@ -470,15 +654,15 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
470
654
  * //
471
655
  * @returns {T} data: T
472
656
  */
473
- async findOne(filter: F): Promise<T> {
474
- let data: T = await this.dataModel.findOne(filter).then(res => {
657
+ async findOne(filterBy: DynamoNTS_DBFilter<T>): Promise<T> {
658
+ let data: T = await this.dataModel.findOne(filterBy).then(res => {
475
659
  return res as T ?? null;
476
660
  }).catch(error => {
477
661
  throw new Dynamo_Error({
478
662
  status: 417,
479
663
  errorCode: 'NTS-DBS-FO0',
480
664
  addECToUserMsg: true,
481
- message: `findOne ${this.dataParams.dbName} was unsuccessful (NTS DB) fliter: ${filter}`,
665
+ message: `findOne ${this.dataParams.dbName} was unsuccessful (NTS DB) fliter: ${filterBy}`,
482
666
  userMessage: this.defaultErrorUserMsg,
483
667
  error
484
668
  });
@@ -496,7 +680,7 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
496
680
  * Find the data first by any of its parameters,
497
681
  * !!!: throws error if not found (errorCode on not found: NTS-DBS-F1)
498
682
  *
499
- * @param filter if you can, use unique parameters for find!
683
+ * @param filterBy if you can, use unique parameters for find!
500
684
  *
501
685
  * @example
502
686
  * // by email:
@@ -518,8 +702,8 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
518
702
  * //
519
703
  * @returns {T[]} dataList: T[]
520
704
  */
521
- async find(filter: F): Promise<T[]> {
522
- let dataList: T[] = await this.dataModel.find(filter)
705
+ async find(filterBy: DynamoNTS_DBFilter<T>): Promise<T[]> {
706
+ let dataList: T[] = await this.dataModel.find(filterBy)
523
707
  .then(res => {
524
708
  return res as T[] ?? [];
525
709
  }).catch(error => {
@@ -548,7 +732,7 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
548
732
  * #MONGOOSE FUNCTION
549
733
  * Find the data first by any of its parameters
550
734
  *
551
- * @param filter if you can, use unique parameters for find!
735
+ * @param filterBy if you can, use unique parameters for find!
552
736
  *
553
737
  * @example
554
738
  * // by email:
@@ -577,8 +761,8 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
577
761
  * //
578
762
  * @returns {T[]} dataList: T[]
579
763
  */
580
- async findWithPaging(filter: F, page: number, pageSize: number, sort?: any): Promise<T[]> {
581
- let dataList: T[] = await this.dataModel.find(filter)
764
+ async findWithPaging(filterBy: DynamoNTS_DBFilter<T>, page: number, pageSize: number, sort?: any): Promise<T[]> {
765
+ let dataList: T[] = await this.dataModel.find(filterBy)
582
766
  .sort(sort)
583
767
  .skip(page * pageSize)
584
768
  .limit(pageSize)
@@ -614,7 +798,7 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
614
798
  * @param update update
615
799
  * @returns data
616
800
  */
617
- async findByIdAndUpdate(id: string, update: U, modifier: string): Promise<T> {
801
+ async findByIdAndUpdate(id: string, update: DynamoNTS_DBUpdate<T>, modifier: string): Promise<T> {
618
802
  update.__lastModified = new Date();
619
803
  update.__lastModifiedBy = modifier;
620
804
 
@@ -690,11 +874,11 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
690
874
  * $unset: // Removes the specified field from a document. (set: "" to value)
691
875
  * //
692
876
  */
693
- async updateOne(updateBy: F, update: U, issuer: string): Promise<void> {
877
+ async updateOne(filterBy: DynamoNTS_DBFilter<T>, update: DynamoNTS_DBUpdate<T>, issuer: string): Promise<void> {
694
878
  update.__lastModified = new Date();
695
879
  update.__lastModifiedBy = issuer;
696
880
 
697
- await this.dataModel.updateOne(updateBy, update).catch(error => {
881
+ await this.dataModel.updateOne(filterBy, update).catch(error => {
698
882
  throw new Dynamo_Error({
699
883
  status: 417,
700
884
  errorCode: 'NTS-DBS-UO0',
@@ -757,11 +941,11 @@ export class DynamoNTS_DBService<T extends Dynamo_Metadata, F extends T = any, U
757
941
  * $unset: // Removes the specified field from a document. (set: "" to value)
758
942
  * //
759
943
  */
760
- async updateMany(updateBy: F, update: U, issuer: string): Promise<void> {
944
+ async updateMany(filterBy: DynamoNTS_DBFilter<T>, update: DynamoNTS_DBUpdate<T>, issuer: string): Promise<void> {
761
945
  update.__lastModified = new Date();
762
946
  update.__lastModifiedBy = issuer;
763
947
 
764
- await this.dataModel.updateMany(updateBy, update).catch(error => {
948
+ await this.dataModel.updateMany(filterBy, update).catch(error => {
765
949
  throw new Dynamo_Error({
766
950
  status: 417,
767
951
  errorCode: 'NTS-DBS-UM0',