@rws-framework/db 2.1.11 → 2.2.1

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 (71) hide show
  1. package/dist/decorators/InverseRelation.d.ts +0 -0
  2. package/dist/decorators/InverseRelation.js +0 -0
  3. package/dist/decorators/InverseTimeSeries.d.ts +0 -0
  4. package/dist/decorators/InverseTimeSeries.js +0 -0
  5. package/dist/decorators/RWSCollection.d.ts +0 -0
  6. package/dist/decorators/RWSCollection.js +0 -0
  7. package/dist/decorators/Relation.d.ts +0 -0
  8. package/dist/decorators/Relation.js +0 -0
  9. package/dist/decorators/TrackType.d.ts +1 -1
  10. package/dist/decorators/TrackType.js +0 -0
  11. package/dist/decorators/index.d.ts +0 -0
  12. package/dist/decorators/index.js +0 -0
  13. package/dist/helper/DbHelper.d.ts +0 -0
  14. package/dist/helper/DbHelper.js +0 -0
  15. package/dist/helper/FieldsHelper.d.ts +0 -0
  16. package/dist/helper/FieldsHelper.js +0 -0
  17. package/dist/index.d.ts +0 -0
  18. package/dist/index.js +0 -0
  19. package/dist/models/TimeSeriesModel.d.ts +0 -0
  20. package/dist/models/TimeSeriesModel.js +0 -0
  21. package/dist/models/_model.d.ts +5 -116
  22. package/dist/models/_model.js +10 -42
  23. package/dist/models/core/RWSModel.d.ts +65 -0
  24. package/dist/models/core/RWSModel.js +375 -0
  25. package/dist/models/core/TimeSeriesModel.d.ts +7 -0
  26. package/dist/models/core/TimeSeriesModel.js +34 -0
  27. package/dist/models/index.d.ts +8 -0
  28. package/dist/models/index.js +12 -0
  29. package/dist/models/interfaces/IModel.d.ts +10 -0
  30. package/dist/models/interfaces/IModel.js +2 -0
  31. package/dist/models/interfaces/IRWSModelServices.d.ts +6 -0
  32. package/dist/models/interfaces/IRWSModelServices.js +2 -0
  33. package/dist/models/interfaces/OpModelType.d.ts +32 -0
  34. package/dist/models/interfaces/OpModelType.js +2 -0
  35. package/dist/models/types/RelationTypes.d.ts +24 -0
  36. package/dist/models/types/RelationTypes.js +2 -0
  37. package/dist/models/utils/ModelUtils.d.ts +10 -0
  38. package/dist/models/utils/ModelUtils.js +56 -0
  39. package/dist/models/utils/PaginationUtils.d.ts +5 -0
  40. package/dist/models/utils/PaginationUtils.js +32 -0
  41. package/dist/models/utils/RelationUtils.d.ts +14 -0
  42. package/dist/models/utils/RelationUtils.js +65 -0
  43. package/dist/models/utils/TimeSeriesUtils.d.ts +11 -0
  44. package/dist/models/utils/TimeSeriesUtils.js +35 -0
  45. package/dist/services/DBService.d.ts +3 -2
  46. package/dist/services/DBService.js +5 -1
  47. package/dist/types/DbConfigHandler.d.ts +1 -1
  48. package/dist/types/DbConfigHandler.js +0 -0
  49. package/dist/types/FindParams.d.ts +5 -0
  50. package/dist/types/FindParams.js +0 -0
  51. package/dist/types/IRWSModel.d.ts +0 -0
  52. package/dist/types/IRWSModel.js +0 -0
  53. package/dist/types/ITimeSeries.d.ts +0 -0
  54. package/dist/types/ITimeSeries.js +0 -0
  55. package/package.json +1 -1
  56. package/src/decorators/TrackType.ts +2 -2
  57. package/src/models/_model.ts +29 -24
  58. package/src/models/core/RWSModel.ts +482 -0
  59. package/src/models/core/TimeSeriesModel.ts +19 -0
  60. package/src/models/index.ts +20 -0
  61. package/src/models/interfaces/IModel.ts +11 -0
  62. package/src/models/interfaces/IRWSModelServices.ts +7 -0
  63. package/src/models/interfaces/OpModelType.ts +49 -0
  64. package/src/models/types/RelationTypes.ts +25 -0
  65. package/src/models/utils/ModelUtils.ts +65 -0
  66. package/src/models/utils/PaginationUtils.ts +42 -0
  67. package/src/models/utils/RelationUtils.ts +76 -0
  68. package/src/models/utils/TimeSeriesUtils.ts +38 -0
  69. package/src/services/DBService.ts +14 -3
  70. package/src/types/DbConfigHandler.ts +2 -2
  71. package/src/types/FindParams.ts +10 -4
@@ -0,0 +1,482 @@
1
+ import { IModel } from '../interfaces/IModel';
2
+ import { IRWSModelServices } from '../interfaces/IRWSModelServices';
3
+ import { OpModelType } from '../interfaces/OpModelType';
4
+ import { TrackType, IMetaOpts } from '../../decorators';
5
+ import { FieldsHelper } from '../../helper/FieldsHelper';
6
+ import { FindByType, IPaginationParams } from '../../types/FindParams';
7
+ import { RelationUtils } from '../utils/RelationUtils';
8
+ import { PaginationUtils } from '../utils/PaginationUtils';
9
+
10
+ import { TimeSeriesUtils } from '../utils/TimeSeriesUtils';
11
+ import { ModelUtils } from '../utils/ModelUtils';
12
+ import timeSeriesModel from './TimeSeriesModel';
13
+ import { DBService } from '../../services/DBService';
14
+
15
+ class RWSModel<ChildClass> implements IModel {
16
+ static services: IRWSModelServices = {};
17
+
18
+ [key: string]: any;
19
+ @TrackType(String)
20
+ id: string;
21
+ static _collection: string = null;
22
+ static _RELATIONS = {};
23
+ static _BANNED_KEYS = ['_collection'];
24
+ static allModels: OpModelType<any>[] = [];
25
+ static _CUT_KEYS: string[] = [];
26
+
27
+ constructor(data: any) {
28
+ if(!this.getCollection()){
29
+ throw new Error('Model must have a collection defined');
30
+ }
31
+
32
+ this.dbService = RWSModel.services.dbService;
33
+ this.configService = RWSModel.services.configService;
34
+
35
+ if(!data){
36
+ return;
37
+ }
38
+
39
+ if(!this.hasTimeSeries()){
40
+ this._fill(data);
41
+ }else{
42
+ throw new Error('Time Series not supported in synchronous constructor. Use `await Model.create(data)` static method to instantiate this model.');
43
+ }
44
+ }
45
+
46
+ checkForInclusionWithThrow(): void {
47
+ this.checkForInclusionWithThrow();
48
+ }
49
+
50
+ static checkForInclusionWithThrow(this: OpModelType<any>, checkModelType: string): void {
51
+ if(!this.checkForInclusion(this.name)){
52
+ throw new Error('Model undefined: ' + this.name);
53
+ }
54
+ }
55
+
56
+ checkForInclusion(): boolean {
57
+ return this.checkForInclusion();
58
+ }
59
+
60
+ static checkForInclusion(this: OpModelType<any>, checkModelType: string): boolean {
61
+ return this.loadModels().find((definedModel: OpModelType<any>) => {
62
+ return definedModel.name === checkModelType;
63
+ }) !== undefined;
64
+ }
65
+
66
+ protected _fill(data: any): RWSModel<ChildClass> {
67
+ for (const key in data) {
68
+ if (data.hasOwnProperty(key)) {
69
+
70
+ const meta = Reflect.getMetadata(`InverseTimeSeries:${key}`, (this as any).constructor.prototype);
71
+
72
+ if(meta){
73
+ data[key] = {
74
+ create: data[key]
75
+ };
76
+ }else{
77
+ this[key] = data[key];
78
+ }
79
+ }
80
+ }
81
+
82
+ return this;
83
+ }
84
+
85
+ protected hasRelation(key: string): boolean {
86
+ return RelationUtils.hasRelation(this, key);
87
+ }
88
+
89
+ protected bindRelation(key: string, relatedModel: RWSModel<any>): { connect: { id: string } } {
90
+ return RelationUtils.bindRelation(relatedModel);
91
+ }
92
+
93
+ public async _asyncFill(data: any, fullDataMode = false, allowRelations = true): Promise<ChildClass> {
94
+ const collections_to_models: {[key: string]: any} = {};
95
+ const timeSeriesIds = TimeSeriesUtils.getTimeSeriesModelFields(this);
96
+
97
+ const classFields = FieldsHelper.getAllClassFields(this.constructor);
98
+
99
+ // Get both relation metadata types asynchronously
100
+ const [relOneData, relManyData] = await Promise.all([
101
+ this.getRelationOneMeta(classFields),
102
+ this.getRelationManyMeta(classFields)
103
+ ]);
104
+
105
+ this.loadModels().forEach((model) => {
106
+ collections_to_models[model.getCollection()] = model;
107
+ });
108
+
109
+ const seriesHydrationfields: string[] = [];
110
+
111
+ if (allowRelations) {
112
+ // Handle many-to-many relations
113
+ for (const key in relManyData) {
114
+ if(!fullDataMode && (this as any).constructor._CUT_KEYS.includes(key)){
115
+ continue;
116
+ }
117
+
118
+ const relMeta = relManyData[key];
119
+
120
+ const relationEnabled = RelationUtils.checkRelEnabled(this, relMeta.key);
121
+ if (relationEnabled) {
122
+ this[relMeta.key] = await relMeta.inversionModel.findBy({
123
+ conditions: {
124
+ [relMeta.foreignKey]: data.id
125
+ },
126
+ allowRelations: false
127
+ });
128
+ }
129
+ }
130
+
131
+ // Handle one-to-one relations
132
+ for (const key in relOneData) {
133
+ if(!fullDataMode && (this as any).constructor._CUT_KEYS.includes(key)){
134
+ continue;
135
+ }
136
+
137
+ const relMeta = relOneData[key];
138
+ const relationEnabled = RelationUtils.checkRelEnabled(this, relMeta.key);
139
+
140
+ if(!data[relMeta.hydrationField] && relMeta.required){
141
+ throw new Error(`Relation field "${relMeta.hydrationField}" is required in model ${this.constructor.name}.`)
142
+ }
143
+
144
+ if (relationEnabled && data[relMeta.hydrationField]) {
145
+ this[relMeta.key] = await relMeta.model.find(data[relMeta.hydrationField], { allowRelations: false });
146
+ }
147
+ else if(relationEnabled && !data[relMeta.hydrationField] && data[relMeta.key]){
148
+ const newRelModel: RWSModel<any> = await relMeta.model.create(data[relMeta.key]);
149
+ this[relMeta.key] = await newRelModel.save();
150
+ }
151
+
152
+ const cutKeys = ((this.constructor as any)._CUT_KEYS as string[]);
153
+
154
+ if(!cutKeys.includes(relMeta.hydrationField)){
155
+ cutKeys.push(relMeta.hydrationField)
156
+ }
157
+ }
158
+ }
159
+
160
+ // Process regular fields and time series
161
+ for (const key in data) {
162
+ if (data.hasOwnProperty(key)) {
163
+ if(!fullDataMode && (this as any).constructor._CUT_KEYS.includes(key)){
164
+ continue;
165
+ }
166
+
167
+ if (Object.keys(relOneData).includes(key)) {
168
+ continue;
169
+ }
170
+
171
+ if (seriesHydrationfields.includes(key)) {
172
+ continue;
173
+ }
174
+
175
+ const timeSeriesMetaData = timeSeriesIds[key];
176
+
177
+ if (timeSeriesMetaData) {
178
+ this[key] = data[key];
179
+ const seriesModel = collections_to_models[timeSeriesMetaData.collection];
180
+
181
+ const dataModels = await seriesModel.findBy({
182
+ id: { in: data[key] }
183
+ });
184
+
185
+ seriesHydrationfields.push(timeSeriesMetaData.hydrationField);
186
+
187
+ this[timeSeriesMetaData.hydrationField] = dataModels;
188
+ } else {
189
+ this[key] = data[key];
190
+ }
191
+ }
192
+ }
193
+
194
+ return this as any as ChildClass;
195
+ }
196
+
197
+ private getModelScalarFields(model: RWSModel<ChildClass>): string[] {
198
+ return ModelUtils.getModelScalarFields(model);
199
+ }
200
+
201
+ private async getRelationOneMeta(classFields: string[]) {
202
+ return RelationUtils.getRelationOneMeta(this, classFields);
203
+ }
204
+
205
+ static async getRelationOneMeta(model: any, classFields: string[]) {
206
+ return RelationUtils.getRelationOneMeta(model, classFields);
207
+ }
208
+
209
+ private async getRelationManyMeta(classFields: string[]) {
210
+ return RelationUtils.getRelationManyMeta(this, classFields);
211
+ }
212
+
213
+ static async getRelationManyMeta(model: any, classFields: string[]) {
214
+ return RelationUtils.getRelationManyMeta(model, classFields);
215
+ }
216
+
217
+ static paginate<ChildClass extends RWSModel<ChildClass>>(this: OpModelType<any>,pageParams: IPaginationParams, findParams?: FindByType): Promise<RWSModel<ChildClass>[]> {
218
+ return PaginationUtils.paginate.bind(this)(pageParams, findParams);
219
+ }
220
+
221
+ public async toMongo(): Promise<any> {
222
+ const data: any = {};
223
+ const timeSeriesIds = TimeSeriesUtils.getTimeSeriesModelFields(this);
224
+ const timeSeriesHydrationFields: string[] = [];
225
+
226
+ for (const key in (this as any)) {
227
+ if (this.hasRelation(key)) {
228
+ data[key] = this.bindRelation(key, this[key]);
229
+ continue;
230
+ }
231
+
232
+ if (!(await this.isDbVariable(key))) {
233
+ continue;
234
+ }
235
+
236
+ const passedFieldCondition: boolean = this.hasOwnProperty(key) &&
237
+ !((this as any).constructor._BANNED_KEYS
238
+ || RWSModel._BANNED_KEYS
239
+ ).includes(key) &&
240
+ !timeSeriesHydrationFields.includes(key)
241
+ ;
242
+
243
+ if (passedFieldCondition) {
244
+ data[key] = this[key];
245
+ }
246
+
247
+ if (timeSeriesIds[key]) {
248
+ data[key] = this[key];
249
+ timeSeriesHydrationFields.push(timeSeriesIds[key].hydrationField);
250
+ }
251
+ }
252
+
253
+ return data;
254
+ }
255
+
256
+ getCollection(): string | null {
257
+ return (this as any).constructor._collection || this._collection;
258
+ }
259
+
260
+ static getCollection(): string | null {
261
+ return (this as any).constructor._collection || this._collection;
262
+ }
263
+
264
+ async save(): Promise<this> {
265
+ const data = await this.toMongo();
266
+ let updatedModelData = data;
267
+ if (this.id) {
268
+ this.preUpdate();
269
+
270
+ updatedModelData = await this.dbService.update(data, this.getCollection());
271
+
272
+ await this._asyncFill(updatedModelData);
273
+ this.postUpdate();
274
+ } else {
275
+ this.preCreate();
276
+
277
+ const isTimeSeries = this instanceof timeSeriesModel;
278
+
279
+ updatedModelData = await this.dbService.insert(data, this.getCollection(), isTimeSeries);
280
+
281
+ await this._asyncFill(updatedModelData);
282
+
283
+ this.postCreate();
284
+ }
285
+
286
+ return this;
287
+ }
288
+
289
+ static async getModelAnnotations<T extends unknown>(constructor: new () => T): Promise<Record<string, {annotationType: string, metadata: any}>> {
290
+ return ModelUtils.getModelAnnotations(constructor);
291
+ }
292
+
293
+ public preUpdate(): void {
294
+ return;
295
+ }
296
+
297
+ public postUpdate(): void {
298
+ return;
299
+ }
300
+
301
+ public preCreate(): void {
302
+ return;
303
+ }
304
+
305
+ public postCreate(): void {
306
+ return;
307
+ }
308
+
309
+ public static isSubclass<T extends RWSModel<T>, C extends new () => T>(constructor: C, baseClass: new () => T): boolean {
310
+ return ModelUtils.isSubclass(constructor, baseClass);
311
+ }
312
+
313
+ hasTimeSeries(): boolean {
314
+ return TimeSeriesUtils.checkTimeSeries((this as any).constructor);
315
+ }
316
+
317
+ static checkTimeSeries(constructor: any): boolean {
318
+ return TimeSeriesUtils.checkTimeSeries(constructor);
319
+ }
320
+
321
+ async isDbVariable(variable: string): Promise<boolean> {
322
+ return ModelUtils.checkDbVariable((this as any).constructor, variable);
323
+ }
324
+
325
+ static async checkDbVariable(constructor: any, variable: string): Promise<boolean> {
326
+ return ModelUtils.checkDbVariable(constructor, variable);
327
+ }
328
+
329
+ sanitizeDBData(data: any): any {
330
+ const dataKeys = Object.keys(data);
331
+ const sanitizedData: {[key: string]: any} = {};
332
+
333
+ for (const key of dataKeys){
334
+ if(this.isDbVariable(key)){
335
+ sanitizedData[key] = data[key];
336
+ }
337
+ }
338
+
339
+ return sanitizedData;
340
+ }
341
+
342
+ public static async watchCollection<ChildClass extends RWSModel<ChildClass>>(
343
+ this: OpModelType<ChildClass>,
344
+ preRun: () => void
345
+ ){
346
+ const collection = Reflect.get(this, '_collection');
347
+ this.checkForInclusionWithThrow(this.name);
348
+ return await this.services.dbService.watchCollection(collection, preRun);
349
+ }
350
+
351
+ public static async findOneBy<ChildClass extends RWSModel<ChildClass>>(
352
+ this: OpModelType<ChildClass>,
353
+ findParams?: FindByType
354
+ ): Promise<ChildClass | null> {
355
+ const conditions = findParams?.conditions ?? {};
356
+ const ordering = findParams?.ordering ?? null;
357
+ const fields = findParams?.fields ?? null;
358
+ const allowRelations = findParams?.allowRelations ?? true;
359
+ const fullData = findParams?.fullData ?? false;
360
+
361
+ this.checkForInclusionWithThrow('');
362
+
363
+
364
+ const collection = Reflect.get(this, '_collection');
365
+ const dbData = await this.services.dbService.findOneBy(collection, conditions, fields, ordering, allowRelations);
366
+
367
+
368
+ if (dbData) {
369
+ const inst: ChildClass = new (this as { new(): ChildClass })();
370
+ return await inst._asyncFill(dbData, fullData, allowRelations);
371
+ }
372
+
373
+ return null;
374
+ }
375
+
376
+ public static async find<ChildClass extends RWSModel<ChildClass>>(
377
+ this: OpModelType<ChildClass>,
378
+ id: string,
379
+ findParams: Omit<FindByType, 'conditions'> = null
380
+ ): Promise<ChildClass | null> {
381
+ const ordering = findParams?.ordering ?? null;
382
+ const fields = findParams?.fields ?? null;
383
+ const allowRelations = findParams?.allowRelations ?? true;
384
+ const fullData = findParams?.fullData ?? false;
385
+
386
+ const collection = Reflect.get(this, '_collection');
387
+ this.checkForInclusionWithThrow(this.name);
388
+
389
+ const dbData = await this.services.dbService.findOneBy(collection, { id }, fields, ordering, allowRelations);
390
+
391
+ if (dbData) {
392
+ const inst: ChildClass = new (this as { new(): ChildClass })();
393
+ return await inst._asyncFill(dbData, fullData, allowRelations);
394
+ }
395
+
396
+ return null;
397
+ }
398
+
399
+ public static async findBy<ChildClass extends RWSModel<ChildClass>>(
400
+ this: OpModelType<ChildClass>,
401
+ findParams?: FindByType
402
+ ): Promise<ChildClass[]> {
403
+ const conditions = findParams?.conditions ?? {};
404
+ const ordering = findParams?.ordering ?? null;
405
+ const fields = findParams?.fields ?? null;
406
+ const allowRelations = findParams?.allowRelations ?? true;
407
+ const fullData = findParams?.fullData ?? false;
408
+
409
+ const collection = Reflect.get(this, '_collection');
410
+ this.checkForInclusionWithThrow(this.name);
411
+ try {
412
+ const dbData = await this.services.dbService.findBy(collection, conditions, fields, ordering);
413
+ if (dbData.length) {
414
+ const instanced: ChildClass[] = [];
415
+
416
+ for (const data of dbData) {
417
+ const inst: ChildClass = new (this as { new(): ChildClass })();
418
+ instanced.push((await inst._asyncFill(data, fullData,allowRelations)) as ChildClass);
419
+ }
420
+
421
+ return instanced;
422
+ }
423
+
424
+ return [];
425
+ } catch (rwsError: Error | any) {
426
+ console.error(rwsError);
427
+
428
+ throw rwsError;
429
+ }
430
+ }
431
+
432
+ public static async delete<ChildClass extends RWSModel<ChildClass>>(
433
+ this: OpModelType<ChildClass>,
434
+ conditions: any
435
+ ): Promise<void> {
436
+ const collection = Reflect.get(this, '_collection');
437
+ this.checkForInclusionWithThrow(this.name);
438
+ return await this.services.dbService.delete(collection, conditions);
439
+ }
440
+
441
+ public async delete<ChildClass extends RWSModel<ChildClass>>(): Promise<void> {
442
+ const collection = Reflect.get(this, '_collection');
443
+ this.checkForInclusionWithThrow();
444
+ return await this.dbService.delete(collection, {
445
+ id: this.id
446
+ });
447
+ }
448
+
449
+ static async create<T extends RWSModel<T>>(this: new () => T, data: any): Promise<T> {
450
+ const newModel = new this();
451
+
452
+ const sanitizedData = newModel.sanitizeDBData(data);
453
+
454
+ await newModel._asyncFill(sanitizedData);
455
+
456
+ return newModel;
457
+ }
458
+
459
+ static loadModels(): OpModelType<any>[] {
460
+ return this.allModels || [];
461
+ }
462
+
463
+ loadModels(): OpModelType<any>[] {
464
+ return RWSModel.loadModels();
465
+ }
466
+
467
+ private checkRelEnabled(key: string): boolean {
468
+ return RelationUtils.checkRelEnabled(this, key);
469
+ }
470
+
471
+ public static setServices(services: IRWSModelServices){
472
+ this.allModels = services.configService.get('db_models');
473
+ this.services = services;
474
+ }
475
+
476
+ public getDb(): DBService
477
+ {
478
+ return this.services.dbService;
479
+ }
480
+ }
481
+
482
+ export { RWSModel };
@@ -0,0 +1,19 @@
1
+ import { RWSModel } from './RWSModel';
2
+ import { TrackType } from '../../decorators';
3
+
4
+ export default class TimeSeriesModel<ChildClass> extends RWSModel<TimeSeriesModel<ChildClass>> {
5
+ @TrackType(Number) value: number;
6
+
7
+ @TrackType(Date) timestamp: Date;
8
+
9
+ @TrackType(Object)
10
+ params: any;
11
+
12
+ constructor(data?: any) {
13
+ super(data);
14
+
15
+ if(!this.timestamp) {
16
+ this.timestamp = new Date();
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,20 @@
1
+ import { IModel } from './interfaces/IModel';
2
+ import { IRWSModelServices } from './interfaces/IRWSModelServices';
3
+ import { OpModelType } from './interfaces/OpModelType';
4
+ import { RelationBindType, RelOneMetaType, RelManyMetaType } from './types/RelationTypes';
5
+ import { RWSModel } from './core/RWSModel';
6
+ import TimeSeriesModel from './core/TimeSeriesModel';
7
+ import { TrackType, IMetaOpts } from '../decorators';
8
+
9
+ export {
10
+ IModel,
11
+ IRWSModelServices,
12
+ OpModelType,
13
+ RelationBindType,
14
+ RelOneMetaType,
15
+ RelManyMetaType,
16
+ RWSModel,
17
+ TimeSeriesModel,
18
+ TrackType,
19
+ IMetaOpts
20
+ };
@@ -0,0 +1,11 @@
1
+ import { IDbConfigHandler } from '../../types/DbConfigHandler';
2
+ import { DBService } from '../../services/DBService';
3
+
4
+ export interface IModel {
5
+ [key: string]: any;
6
+ id: string | null;
7
+ save: () => void;
8
+ getCollection: () => string | null;
9
+ configService?: IDbConfigHandler;
10
+ dbService?: DBService;
11
+ }
@@ -0,0 +1,7 @@
1
+ import { IDbConfigHandler } from '../../types/DbConfigHandler';
2
+ import { DBService } from '../../services/DBService';
3
+
4
+ export interface IRWSModelServices {
5
+ configService?: IDbConfigHandler;
6
+ dbService?: DBService;
7
+ }
@@ -0,0 +1,49 @@
1
+ import { IRWSModel } from '../../types/IRWSModel';
2
+ import { FindByType, IPaginationParams } from '../../types/FindParams';
3
+ import { IRWSModelServices } from './IRWSModelServices';
4
+ import { RelOneMetaType, RelManyMetaType } from '../types/RelationTypes';
5
+ import { DBService } from '../../services/DBService';
6
+
7
+ // Forward declaration to avoid circular dependency
8
+ type RWSModel<T> = any;
9
+
10
+ export interface OpModelType<ChildClass> {
11
+ new(data?: any | null): ChildClass;
12
+ services: IRWSModelServices;
13
+ name: string;
14
+ _collection: string;
15
+ _RELATIONS: {[key: string]: boolean};
16
+ _CUT_KEYS: string[];
17
+ allModels: OpModelType<any>[];
18
+ loadModels: () => OpModelType<any>[];
19
+ checkForInclusionWithThrow: (className: string) => void;
20
+ checkForInclusion: (className: string) => boolean;
21
+ findOneBy<T extends RWSModel<T>>(
22
+ this: OpModelType<T>,
23
+ findParams: FindByType
24
+ ): Promise<T | null>;
25
+ find<T extends RWSModel<T>>(
26
+ this: OpModelType<T>,
27
+ id: string,
28
+ findParams?: Omit<FindByType, 'conditions'>
29
+ ): Promise<T | null>;
30
+ findBy<T extends RWSModel<T>>(
31
+ this: OpModelType<T>,
32
+ findParams: FindByType
33
+ ): Promise<T[]>;
34
+ paginate<T extends RWSModel<T>>(
35
+ this: OpModelType<T>,
36
+ paginateParams?: IPaginationParams,
37
+ findParams?: FindByType
38
+ ): Promise<T[]>;
39
+ delete<ChildClass extends RWSModel<ChildClass>>(
40
+ this: OpModelType<ChildClass>,
41
+ conditions: any
42
+ ): Promise<void>;
43
+ create<T extends RWSModel<T>>(this: OpModelType<T>, data: T): Promise<T>;
44
+ getRelationOneMeta(model: any, classFields: string[]): Promise<RelOneMetaType<IRWSModel>>;
45
+ getRelationManyMeta(model: any, classFields: string[]): Promise<RelManyMetaType<IRWSModel>>;
46
+ getCollection(): string;
47
+ getDb(): DBService;
48
+ setServices(services: IRWSModelServices): void;
49
+ }
@@ -0,0 +1,25 @@
1
+ import { IRWSModel } from '../../types/IRWSModel';
2
+ // Using a type reference to avoid circular dependency
3
+ type OpModelType<T> = any;
4
+
5
+ export type RelationBindType = {
6
+ connect: { id: string }
7
+ };
8
+
9
+ export type RelOneMetaType<T extends IRWSModel> = {
10
+ [key: string]: {
11
+ required: boolean,
12
+ key?: string,
13
+ model: OpModelType<T>,
14
+ hydrationField: string,
15
+ foreignKey: string
16
+ }
17
+ };
18
+
19
+ export type RelManyMetaType<T extends IRWSModel> = {
20
+ [key: string]: {
21
+ key: string,
22
+ inversionModel: OpModelType<T>,
23
+ foreignKey: string
24
+ }
25
+ };
@@ -0,0 +1,65 @@
1
+ import { RWSModel } from "../core/RWSModel";
2
+ import { FieldsHelper } from '../../helper/FieldsHelper';
3
+
4
+ export class ModelUtils {
5
+ static async getModelAnnotations<T extends unknown>(constructor: new () => T): Promise<Record<string, {annotationType: string, metadata: any}>> {
6
+ const annotationsData: Record<string, {annotationType: string, metadata: any}> = {};
7
+
8
+ const metadataKeys = Reflect.getMetadataKeys(constructor.prototype);
9
+
10
+ // Process all metadata keys and collect promises
11
+ const metadataPromises = metadataKeys.map(async (fullKey: string) => {
12
+ const [annotationType, propertyKey] = fullKey.split(':');
13
+ const metadata = Reflect.getMetadata(fullKey, constructor.prototype);
14
+
15
+ if (metadata) {
16
+ // If this is a relation metadata with a promise
17
+ if (metadata.promise && (annotationType === 'Relation' || annotationType === 'InverseRelation')) {
18
+ const resolvedMetadata = await metadata.promise;
19
+ annotationsData[propertyKey] = {
20
+ annotationType,
21
+ metadata: resolvedMetadata
22
+ };
23
+ } else {
24
+ // Handle non-relation metadata as before
25
+ const key = metadata.key || propertyKey;
26
+ annotationsData[key] = {
27
+ annotationType,
28
+ metadata
29
+ };
30
+ }
31
+ }
32
+ });
33
+
34
+ // Wait for all metadata to be processed
35
+ await Promise.all(metadataPromises);
36
+
37
+ return annotationsData;
38
+ }
39
+
40
+ static async checkDbVariable(constructor: any, variable: string): Promise<boolean> {
41
+ if(variable === 'id'){
42
+ return true;
43
+ }
44
+
45
+ const dbAnnotations = await ModelUtils.getModelAnnotations(constructor);
46
+ type AnnotationType = { annotationType: string, key: string };
47
+
48
+ const dbProperties: string[] = Object.keys(dbAnnotations)
49
+ .map((key: string): AnnotationType => {return {...dbAnnotations[key], key};})
50
+ .filter((element: AnnotationType) => element.annotationType === 'TrackType' )
51
+ .map((element: AnnotationType) => element.key);
52
+
53
+ return dbProperties.includes(variable);
54
+ }
55
+
56
+ static isSubclass<T, C extends new () => T>(constructor: C, baseClass: new () => T): boolean {
57
+ return baseClass.prototype.isPrototypeOf(constructor.prototype);
58
+ }
59
+
60
+ static getModelScalarFields(model: RWSModel<any>): string[] {
61
+ return FieldsHelper.getAllClassFields(model)
62
+ .filter((item: string) => item.indexOf('TrackType') === 0)
63
+ .map((item: string) => item.split(':').at(-1));
64
+ }
65
+ }