@rws-framework/db 2.1.11 → 2.2.0

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.
Files changed (49) hide show
  1. package/README.md +26 -17
  2. package/dist/decorators/TrackType.d.ts +1 -1
  3. package/dist/models/_model.d.ts +5 -116
  4. package/dist/models/_model.js +7 -497
  5. package/dist/models/core/RWSModel.d.ts +65 -0
  6. package/dist/models/core/RWSModel.js +375 -0
  7. package/dist/models/core/TimeSeriesModel.d.ts +7 -0
  8. package/dist/models/core/TimeSeriesModel.js +34 -0
  9. package/dist/models/index.d.ts +8 -0
  10. package/dist/models/index.js +12 -0
  11. package/dist/models/interfaces/IModel.d.ts +10 -0
  12. package/dist/models/interfaces/IModel.js +2 -0
  13. package/dist/models/interfaces/IRWSModelServices.d.ts +6 -0
  14. package/dist/models/interfaces/IRWSModelServices.js +2 -0
  15. package/dist/models/interfaces/OpModelType.d.ts +32 -0
  16. package/dist/models/interfaces/OpModelType.js +2 -0
  17. package/dist/models/types/RelationTypes.d.ts +24 -0
  18. package/dist/models/types/RelationTypes.js +2 -0
  19. package/dist/models/utils/ModelUtils.d.ts +10 -0
  20. package/dist/models/utils/ModelUtils.js +56 -0
  21. package/dist/models/utils/PaginationUtils.d.ts +5 -0
  22. package/dist/models/utils/PaginationUtils.js +32 -0
  23. package/dist/models/utils/RelationUtils copy.d.ts +13 -0
  24. package/dist/models/utils/RelationUtils copy.js +65 -0
  25. package/dist/models/utils/RelationUtils.d.ts +14 -0
  26. package/dist/models/utils/RelationUtils.js +65 -0
  27. package/dist/models/utils/TimeSeriesUtils.d.ts +11 -0
  28. package/dist/models/utils/TimeSeriesUtils.js +35 -0
  29. package/dist/services/DBService.d.ts +3 -2
  30. package/dist/services/DBService.js +5 -1
  31. package/dist/types/DbConfigHandler.d.ts +1 -1
  32. package/dist/types/FindParams.d.ts +5 -0
  33. package/package.json +1 -1
  34. package/src/decorators/TrackType.ts +2 -2
  35. package/src/models/_model.ts +26 -675
  36. package/src/models/core/RWSModel.ts +482 -0
  37. package/src/models/core/TimeSeriesModel.ts +19 -0
  38. package/src/models/index.ts +20 -0
  39. package/src/models/interfaces/IModel.ts +11 -0
  40. package/src/models/interfaces/IRWSModelServices.ts +7 -0
  41. package/src/models/interfaces/OpModelType.ts +49 -0
  42. package/src/models/types/RelationTypes.ts +25 -0
  43. package/src/models/utils/ModelUtils.ts +65 -0
  44. package/src/models/utils/PaginationUtils.ts +42 -0
  45. package/src/models/utils/RelationUtils.ts +76 -0
  46. package/src/models/utils/TimeSeriesUtils.ts +38 -0
  47. package/src/services/DBService.ts +14 -3
  48. package/src/types/DbConfigHandler.ts +2 -2
  49. package/src/types/FindParams.ts +10 -4
@@ -1,676 +1,27 @@
1
- import {DBService, IDBClientCreate} from '../services/DBService';
2
- import { IRWSModel } from '../types/IRWSModel';
3
- import { IDbConfigHandler } from '../types/DbConfigHandler';
4
-
5
- import {TrackType, IMetaOpts } from '../decorators';
6
- import { FieldsHelper } from '../helper/FieldsHelper';
7
- import { FindByType } from '../types/FindParams';
8
-
9
- interface IModel{
10
- [key: string]: any;
11
- id: string | null;
12
- save: () => void;
13
- getCollection: () => string | null;
14
- configService?: IDbConfigHandler;
15
- dbService?: DBService;
16
- }
17
-
18
- interface IRWSModelServices {
19
- configService?: IDbConfigHandler
20
- dbService?: DBService
21
- }
22
-
23
- type RelationBindType = {
24
- connect: { id: string }
1
+ /**
2
+ * @deprecated This file is deprecated. Import from 'models' directory instead.
3
+ */
4
+
5
+ import {
6
+ IModel,
7
+ IRWSModelServices,
8
+ OpModelType,
9
+ RelationBindType,
10
+ RelOneMetaType,
11
+ RelManyMetaType,
12
+ RWSModel,
13
+ TrackType,
14
+ IMetaOpts
15
+ } from './index';
16
+
17
+ export {
18
+ IModel,
19
+ IRWSModelServices,
20
+ OpModelType,
21
+ RelationBindType,
22
+ RelOneMetaType,
23
+ RelManyMetaType,
24
+ RWSModel,
25
+ TrackType,
26
+ IMetaOpts
25
27
  };
26
-
27
- type RelOneMetaType<T extends IRWSModel> = {[key: string]: {required: boolean, key?: string, model: OpModelType<T>, hydrationField: string, foreignKey: string}};
28
- type RelManyMetaType<T extends IRWSModel> = {[key: string]: {key: string, inversionModel: OpModelType<T>, foreignKey: string}};
29
-
30
- export interface OpModelType<ChildClass> {
31
- new(data?: any | null): ChildClass;
32
- services: IRWSModelServices;
33
- name: string
34
- _collection: string;
35
- _RELATIONS: {[key: string]: boolean}
36
- _CUT_KEYS: string[]
37
- allModels: OpModelType<any>[];
38
- loadModels: () => OpModelType<any>[];
39
- checkForInclusionWithThrow: (className: string) => void;
40
- checkForInclusion: (className: string) => boolean;
41
- findOneBy<T extends RWSModel<T>>(
42
- this: OpModelType<T>,
43
- findParams: FindByType
44
- ): Promise<T | null>;
45
- find<T extends RWSModel<T>>(
46
- this: OpModelType<T>,
47
- id: string,
48
- findParams?: Omit<FindByType, 'conditions'>
49
- ): Promise<T | null>;
50
- findBy<T extends RWSModel<T>>(
51
- this: OpModelType<T>,
52
- findParams: FindByType
53
- ): Promise<T[]>;
54
- delete<ChildClass extends RWSModel<ChildClass>>(
55
- this: OpModelType<ChildClass>,
56
- conditions: any
57
- ): Promise<void>
58
- create<T extends RWSModel<T>>(this: OpModelType<T>, data: T): Promise<T>;
59
- getRelationOneMeta(model: any, classFields: string[]): Promise<RelOneMetaType<IRWSModel>>;
60
- getRelationManyMeta(model: any, classFields: string[]): Promise<RelManyMetaType<IRWSModel>>;
61
- getCollection(): string;
62
- setServices(services: IRWSModelServices): void;
63
- }
64
-
65
- class RWSModel<ChildClass> implements IModel{
66
- static services: IRWSModelServices = {};
67
-
68
- [key: string]: any;
69
- @TrackType(String)
70
- id: string;
71
- static _collection: string = null;
72
- static _RELATIONS = {};
73
- static _BANNED_KEYS = ['_collection'];
74
- static allModels: OpModelType<any>[] = [];
75
- static _CUT_KEYS: string[] = [];
76
-
77
- constructor(data: any) {
78
- if(!this.getCollection()){
79
- throw new Error('Model must have a collection defined');
80
-
81
- }
82
-
83
- this.dbService = RWSModel.services.dbService;
84
- this.configService = RWSModel.services.configService;
85
-
86
- if(!data){
87
- return;
88
- }
89
-
90
- if(!this.hasTimeSeries()){
91
- this._fill(data);
92
- }else{
93
- throw new Error('Time Series not supported in synchronous constructor. Use `await Model.create(data)` static method to instantiate this model.');
94
- }
95
- }
96
-
97
- checkForInclusionWithThrow(): void
98
- {
99
- this.checkForInclusionWithThrow();
100
- }
101
-
102
- static checkForInclusionWithThrow(this: OpModelType<any>, checkModelType: string): void
103
- {
104
- if(!this.checkForInclusion(this.name)){
105
- throw new Error('Model undefined: ' + this.name);
106
- }
107
- }
108
-
109
- checkForInclusion(): boolean
110
- {
111
- return this.checkForInclusion();
112
- }
113
-
114
- static checkForInclusion(this: OpModelType<any>, checkModelType: string): boolean
115
- {
116
- return this.loadModels().find((definedModel: OpModelType<any>) => {
117
- return definedModel.name === checkModelType;
118
- }) !== undefined;
119
- }
120
-
121
- _fill(data: any): RWSModel<ChildClass>{
122
- for (const key in data) {
123
- if (data.hasOwnProperty(key)) {
124
-
125
- const meta = Reflect.getMetadata(`InverseTimeSeries:${key}`, (this as any).constructor.prototype);
126
-
127
- if(meta){
128
- data[key] = {
129
- create: data[key]
130
- };
131
- }else{
132
- this[key] = data[key];
133
- }
134
- }
135
- }
136
-
137
- return this;
138
- }
139
-
140
- protected hasRelation(key: string): boolean
141
- {
142
- return !!this[key] && this[key] instanceof RWSModel;
143
- }
144
-
145
- protected bindRelation(key: string, relatedModel: RWSModel<any>): RelationBindType
146
- {
147
- return {
148
- connect: {
149
- id: relatedModel.id
150
- }
151
- };
152
- }
153
-
154
- public async _asyncFill(data: any, fullDataMode = false, allowRelations = true): Promise<ChildClass> {
155
- const collections_to_models: {[key: string]: any} = {};
156
- const timeSeriesIds = this.getTimeSeriesModelFields();
157
-
158
- const classFields = FieldsHelper.getAllClassFields(this.constructor);
159
-
160
- // Get both relation metadata types asynchronously
161
- const [relOneData, relManyData] = await Promise.all([
162
- this.getRelationOneMeta(classFields),
163
- this.getRelationManyMeta(classFields)
164
- ]);
165
-
166
- this.loadModels().forEach((model) => {
167
- collections_to_models[model.getCollection()] = model;
168
- });
169
-
170
- const seriesHydrationfields: string[] = [];
171
-
172
- if (allowRelations) {
173
- for (const key in relManyData) {
174
- if(!fullDataMode && (this as any).constructor._CUT_KEYS.includes(key)){
175
- continue;
176
- }
177
-
178
- const relMeta = relManyData[key];
179
-
180
- const relationEnabled = this.checkRelEnabled(relMeta.key);
181
- if (relationEnabled) {
182
- this[relMeta.key] = await relMeta.inversionModel.findBy({
183
- conditions: {
184
- [relMeta.foreignKey]: data.id
185
- },
186
- allowRelations: false
187
- });
188
- }
189
- }
190
-
191
- for (const key in relOneData) {
192
- if(!fullDataMode && (this as any).constructor._CUT_KEYS.includes(key)){
193
- continue;
194
- }
195
-
196
- const relMeta = relOneData[key];
197
- const relationEnabled = this.checkRelEnabled(relMeta.key);
198
-
199
- if(!data[relMeta.hydrationField] && relMeta.required){
200
- throw new Error(`Relation field "${relMeta.hydrationField}" is required in model ${this.constructor.name}.`)
201
- }
202
-
203
- if (relationEnabled && data[relMeta.hydrationField]) {
204
- this[relMeta.key] = await relMeta.model.find(data[relMeta.hydrationField], { allowRelations: false });
205
- }
206
- else if(relationEnabled && !data[relMeta.hydrationField] && data[relMeta.key]){
207
- const newRelModel: RWSModel<any> = await relMeta.model.create(data[relMeta.key]);
208
- this[relMeta.key] = await newRelModel.save();
209
- }
210
-
211
- const cutKeys = ((this.constructor as any)._CUT_KEYS as string[]);
212
-
213
- if(!cutKeys.includes(relMeta.hydrationField)){
214
- cutKeys.push(relMeta.hydrationField)
215
- }
216
- }
217
- }
218
-
219
- // Process regular fields and time series
220
- for (const key in data) {
221
- if (data.hasOwnProperty(key)) {
222
- if(!fullDataMode && (this as any).constructor._CUT_KEYS.includes(key)){
223
- continue;
224
- }
225
-
226
- if (Object.keys(relOneData).includes(key)) {
227
- continue;
228
- }
229
-
230
- if (seriesHydrationfields.includes(key)) {
231
- continue;
232
- }
233
-
234
- const timeSeriesMetaData = timeSeriesIds[key];
235
-
236
- if (timeSeriesMetaData) {
237
- this[key] = data[key];
238
- const seriesModel = collections_to_models[timeSeriesMetaData.collection];
239
-
240
- const dataModels = await seriesModel.findBy({
241
- id: { in: data[key] }
242
- });
243
-
244
- seriesHydrationfields.push(timeSeriesMetaData.hydrationField);
245
-
246
- this[timeSeriesMetaData.hydrationField] = dataModels;
247
- } else {
248
- this[key] = data[key];
249
- }
250
- }
251
- }
252
-
253
- return this as any as ChildClass;
254
- }
255
-
256
- private getModelScalarFields(model: OpModelType<any>): string[]
257
- {
258
- return FieldsHelper.getAllClassFields(model)
259
- .filter(item => item.indexOf('TrackType') === 0)
260
- .map(item => item.split(':').at(-1))
261
- }
262
-
263
- private getTimeSeriesModelFields()
264
- {
265
- const timeSeriesIds: {[key: string]: {collection: string, hydrationField: string, ids: string[]}} = {};
266
-
267
- for (const key in this as any) {
268
- if (this.hasOwnProperty(key)) {
269
-
270
- const meta = Reflect.getMetadata(`InverseTimeSeries:${key}`, (this as any));
271
- if(meta){
272
- if(!timeSeriesIds[key]){
273
- timeSeriesIds[key] = {
274
- collection: meta.timeSeriesModel,
275
- hydrationField: meta.hydrationField,
276
- ids: this[key]
277
- };
278
- }
279
- }
280
- }
281
- }
282
-
283
- return timeSeriesIds;
284
- }
285
-
286
- private async getRelationOneMeta(classFields: string[]): Promise<RelOneMetaType<RWSModel<any>>> {
287
- return RWSModel.getRelationOneMeta(this, classFields);
288
- }
289
-
290
- static async getRelationOneMeta(model: any, classFields: string[]): Promise<RelOneMetaType<RWSModel<any>>>
291
- {
292
- const relIds: RelOneMetaType<RWSModel<any>> = {};
293
- const relationFields = classFields
294
- .filter((item: string) => item.indexOf('Relation') === 0 && !item.includes('Inverse'))
295
- .map((item: string) => item.split(':').at(-1));
296
-
297
- for (const key of relationFields) {
298
- const metadataKey = `Relation:${key}`;
299
- const metadata = Reflect.getMetadata(metadataKey, model);
300
-
301
- if (metadata && metadata.promise) {
302
- const resolvedMetadata = await metadata.promise;
303
- if (!relIds[key]) {
304
- relIds[key] = {
305
- key: resolvedMetadata.key,
306
- required: resolvedMetadata.required,
307
- model: resolvedMetadata.relatedTo,
308
- hydrationField: resolvedMetadata.relationField,
309
- foreignKey: resolvedMetadata.relatedToField
310
- };
311
- }
312
- }
313
- }
314
-
315
- return relIds;
316
- }
317
-
318
- private async getRelationManyMeta(classFields: string[]): Promise<RelManyMetaType<RWSModel<any>>> {
319
- return RWSModel.getRelationManyMeta(this, classFields);
320
- }
321
-
322
- static async getRelationManyMeta(model: any, classFields: string[]): Promise<RelManyMetaType<RWSModel<any>>>
323
- {
324
- const relIds: RelManyMetaType<RWSModel<any>> = {};
325
-
326
- const inverseFields = classFields
327
- .filter((item: string) => item.indexOf('InverseRelation') === 0)
328
- .map((item: string) => item.split(':').at(-1));
329
-
330
- for (const key of inverseFields) {
331
- const metadataKey = `InverseRelation:${key}`;
332
- const metadata = Reflect.getMetadata(metadataKey, model);
333
-
334
- if (metadata && metadata.promise) {
335
- const resolvedMetadata = await metadata.promise;
336
- if (!relIds[key]) {
337
- relIds[key] = {
338
- key: resolvedMetadata.key,
339
- inversionModel: resolvedMetadata.inversionModel,
340
- foreignKey: resolvedMetadata.foreignKey
341
- };
342
- }
343
- }
344
- }
345
-
346
- return relIds;
347
- }
348
-
349
- public async toMongo(): Promise<any> {
350
- const data: any = {};
351
- const timeSeriesIds = this.getTimeSeriesModelFields();
352
- const timeSeriesHydrationFields: string[] = [];
353
-
354
- for (const key in (this as any)) {
355
- if (this.hasRelation(key)) {
356
- data[key] = this.bindRelation(key, this[key]);
357
- continue;
358
- }
359
-
360
- if (!(await this.isDbVariable(key))) {
361
- continue;
362
- }
363
-
364
- const passedFieldCondition: boolean = this.hasOwnProperty(key) &&
365
- !((this as any).constructor._BANNED_KEYS
366
- || RWSModel._BANNED_KEYS
367
- ).includes(key) &&
368
- !timeSeriesHydrationFields.includes(key)
369
- ;
370
-
371
- if (passedFieldCondition) {
372
- data[key] = this[key];
373
- }
374
-
375
- if (timeSeriesIds[key]) {
376
- data[key] = this[key];
377
- timeSeriesHydrationFields.push(timeSeriesIds[key].hydrationField);
378
- }
379
- }
380
-
381
- return data;
382
- }
383
-
384
- getCollection(): string | null {
385
- return (this as any).constructor._collection || this._collection;
386
- }
387
-
388
- static getCollection(): string | null {
389
- return (this as any).constructor._collection || this._collection;
390
- }
391
-
392
-
393
- async save(): Promise<this> {
394
- const data = await this.toMongo();
395
- let updatedModelData = data;
396
- if (this.id) {
397
- this.preUpdate();
398
-
399
- updatedModelData = await this.dbService.update(data, this.getCollection());
400
-
401
- await this._asyncFill(updatedModelData);
402
- this.postUpdate();
403
- } else {
404
- this.preCreate();
405
-
406
- const timeSeriesModel = await import('./TimeSeriesModel');
407
- const isTimeSeries = this instanceof timeSeriesModel.default;
408
-
409
- updatedModelData = await this.dbService.insert(data, this.getCollection(), isTimeSeries);
410
-
411
- await this._asyncFill(updatedModelData);
412
-
413
- this.postCreate();
414
- }
415
-
416
- return this;
417
- }
418
-
419
- static async getModelAnnotations<T extends unknown>(constructor: new () => T): Promise<Record<string, {annotationType: string, metadata: any}>> {
420
- const annotationsData: Record<string, {annotationType: string, metadata: any}> = {};
421
-
422
- const metadataKeys = Reflect.getMetadataKeys(constructor.prototype);
423
-
424
- // Process all metadata keys and collect promises
425
- const metadataPromises = metadataKeys.map(async (fullKey: string) => {
426
- const [annotationType, propertyKey] = fullKey.split(':');
427
- const metadata = Reflect.getMetadata(fullKey, constructor.prototype);
428
-
429
- if (metadata) {
430
- // If this is a relation metadata with a promise
431
- if (metadata.promise && (annotationType === 'Relation' || annotationType === 'InverseRelation')) {
432
- const resolvedMetadata = await metadata.promise;
433
- annotationsData[propertyKey] = {
434
- annotationType,
435
- metadata: resolvedMetadata
436
- };
437
- } else {
438
- // Handle non-relation metadata as before
439
- const key = metadata.key || propertyKey;
440
- annotationsData[key] = {
441
- annotationType,
442
- metadata
443
- };
444
- }
445
- }
446
- });
447
-
448
- // Wait for all metadata to be processed
449
- await Promise.all(metadataPromises);
450
-
451
- return annotationsData;
452
- }
453
-
454
- public preUpdate(): void
455
- {
456
- return;
457
- }
458
-
459
- public postUpdate(): void
460
- {
461
- return;
462
- }
463
-
464
- public preCreate(): void
465
- {
466
- return;
467
- }
468
-
469
- public postCreate(): void
470
- {
471
- return;
472
- }
473
-
474
- public static isSubclass<T extends RWSModel<T>, C extends new () => T>(constructor: C, baseClass: new () => T): boolean {
475
- return baseClass.prototype.isPrototypeOf(constructor.prototype);
476
- }
477
-
478
- hasTimeSeries(): boolean
479
- {
480
- return RWSModel.checkTimeSeries((this as any).constructor);
481
- }
482
-
483
- static checkTimeSeries(constructor: any): boolean
484
- {
485
- const data = constructor.prototype as any;
486
-
487
- for (const key in data) {
488
-
489
- if (data.hasOwnProperty(key)) {
490
-
491
- if(Reflect.getMetadata(`InverseTimeSeries:${key}`, constructor.prototype)){
492
- return true;
493
- }
494
- }
495
- }
496
-
497
- return false;
498
- }
499
-
500
- async isDbVariable(variable: string): Promise<boolean>
501
- {
502
- return RWSModel.checkDbVariable((this as any).constructor, variable);
503
- }
504
-
505
- static async checkDbVariable(constructor: any, variable: string): Promise<boolean> {
506
- if(variable === 'id'){
507
- return true;
508
- }
509
-
510
- const dbAnnotations = await RWSModel.getModelAnnotations(constructor);
511
- type AnnotationType = { annotationType: string, key: string };
512
-
513
- const dbProperties: string[] = Object.keys(dbAnnotations)
514
- .map((key: string): AnnotationType => {return {...dbAnnotations[key], key};})
515
- .filter((element: AnnotationType) => element.annotationType === 'TrackType' )
516
- .map((element: AnnotationType) => element.key);
517
-
518
- return dbProperties.includes(variable);
519
- }
520
-
521
- sanitizeDBData(data: any): any
522
- {
523
- const dataKeys = Object.keys(data);
524
- const sanitizedData: {[key: string]: any} = {};
525
-
526
- for (const key of dataKeys){
527
- if(this.isDbVariable(key)){
528
- sanitizedData[key] = data[key];
529
- }
530
- }
531
-
532
- return sanitizedData;
533
- }
534
-
535
- public static async watchCollection<ChildClass extends RWSModel<ChildClass>>(
536
- this: OpModelType<ChildClass>,
537
- preRun: () => void
538
- ){
539
- const collection = Reflect.get(this, '_collection');
540
- this.checkForInclusionWithThrow(this.name);
541
- return await this.services.dbService.watchCollection(collection, preRun);
542
- }
543
-
544
- public static async findOneBy<ChildClass extends RWSModel<ChildClass>>(
545
- this: OpModelType<ChildClass>,
546
- findParams?: FindByType
547
- ): Promise<ChildClass | null> {
548
- const conditions = findParams?.conditions ?? {};
549
- const ordering = findParams?.ordering ?? null;
550
- const fields = findParams?.fields ?? null;
551
- const allowRelations = findParams?.allowRelations ?? true;
552
- const fullData = findParams?.fullData ?? false;
553
-
554
- this.checkForInclusionWithThrow('');
555
-
556
-
557
- const collection = Reflect.get(this, '_collection');
558
- const dbData = await this.services.dbService.findOneBy(collection, conditions, fields, ordering, allowRelations);
559
-
560
-
561
- if (dbData) {
562
- const inst: ChildClass = new (this as { new(): ChildClass })();
563
- return await inst._asyncFill(dbData, fullData, allowRelations);
564
- }
565
-
566
- return null;
567
- }
568
-
569
- public static async find<ChildClass extends RWSModel<ChildClass>>(
570
- this: OpModelType<ChildClass>,
571
- id: string,
572
- findParams: Omit<FindByType, 'conditions'> = null
573
- ): Promise<ChildClass | null> {
574
- const ordering = findParams?.ordering ?? null;
575
- const fields = findParams?.fields ?? null;
576
- const allowRelations = findParams?.allowRelations ?? true;
577
- const fullData = findParams?.fullData ?? false;
578
-
579
- const collection = Reflect.get(this, '_collection');
580
- this.checkForInclusionWithThrow(this.name);
581
-
582
- const dbData = await this.services.dbService.findOneBy(collection, { id }, fields, ordering, allowRelations);
583
-
584
- if (dbData) {
585
- const inst: ChildClass = new (this as { new(): ChildClass })();
586
- return await inst._asyncFill(dbData, fullData, allowRelations);
587
- }
588
-
589
- return null;
590
- }
591
-
592
- public static async findBy<ChildClass extends RWSModel<ChildClass>>(
593
- this: OpModelType<ChildClass>,
594
- findParams?: FindByType
595
- ): Promise<ChildClass[]> {
596
- const conditions = findParams?.conditions ?? {};
597
- const ordering = findParams?.ordering ?? null;
598
- const fields = findParams?.fields ?? null;
599
- const allowRelations = findParams?.allowRelations ?? true;
600
- const fullData = findParams?.fullData ?? false;
601
-
602
- const collection = Reflect.get(this, '_collection');
603
- this.checkForInclusionWithThrow(this.name);
604
- try {
605
- const dbData = await this.services.dbService.findBy(collection, conditions, fields, ordering, allowRelations);
606
- if (dbData.length) {
607
- const instanced: ChildClass[] = [];
608
-
609
- for (const data of dbData) {
610
- const inst: ChildClass = new (this as { new(): ChildClass })();
611
- instanced.push((await inst._asyncFill(data, fullData,allowRelations)) as ChildClass);
612
- }
613
-
614
- return instanced;
615
- }
616
-
617
- return [];
618
- } catch (rwsError: Error | any) {
619
- console.error(rwsError);
620
-
621
- throw rwsError;
622
- }
623
- }
624
-
625
- public static async delete<ChildClass extends RWSModel<ChildClass>>(
626
- this: OpModelType<ChildClass>,
627
- conditions: any
628
- ): Promise<void> {
629
- const collection = Reflect.get(this, '_collection');
630
- this.checkForInclusionWithThrow(this.name);
631
- return await this.services.dbService.delete(collection, conditions);
632
- }
633
-
634
- public async delete<ChildClass extends RWSModel<ChildClass>>(): Promise<void> {
635
- const collection = Reflect.get(this, '_collection');
636
- this.checkForInclusionWithThrow();
637
- return await this.dbService.delete(collection, {
638
- id: this.id
639
- });
640
- }
641
-
642
-
643
- static async create<T extends RWSModel<T>>(this: new () => T, data: any): Promise<T> {
644
- const newModel = new this();
645
-
646
- const sanitizedData = newModel.sanitizeDBData(data);
647
-
648
- await newModel._asyncFill(sanitizedData);
649
-
650
- return newModel;
651
- }
652
-
653
- static loadModels(): OpModelType<any>[]
654
- {
655
- return this.allModels || [];
656
- }
657
-
658
- loadModels(): OpModelType<any>[]
659
- {
660
- return RWSModel.loadModels();
661
- }
662
-
663
- private checkRelEnabled(key: string): boolean
664
- {
665
- return Object.keys((this as any).constructor._RELATIONS).includes(key) && (this as any).constructor._RELATIONS[key] === true
666
- }
667
-
668
- public static setServices(services: IRWSModelServices){
669
- this.allModels = services.configService.get('db_models');
670
- this.services = services;
671
- }
672
- }
673
-
674
- export { IModel, TrackType, IMetaOpts, RWSModel };
675
-
676
-