@prestizni-software/server-dem 0.2.22 → 0.2.23

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.
@@ -1,532 +0,0 @@
1
- import "reflect-metadata";
2
- import {
3
- Constructor,
4
- DeRef,
5
- InstanceOf,
6
- IsData,
7
- LoggersType,
8
- LoggersTypeInternal,
9
- Paths,
10
- PathValueOf,
11
- RefToId,
12
- ServerResponse,
13
- ServerUpdateRequest,
14
- SocketType,
15
- } from "./CommonTypes.js";
16
- import { AutoUpdateManager } from "./AutoUpdateManagerClass.js";
17
- import { ObjectId } from "bson";
18
- import { AutoUpdateClientManager } from "./AutoUpdateClientManagerClass.js";
19
-
20
- export type AutoUpdated<T extends Constructor<any>> =
21
- AutoUpdatedClientObject<T> & DeRef<InstanceOf<T>>;
22
- export async function createAutoUpdatedClass<C extends Constructor<any>>(
23
- classParam: C,
24
- socket: SocketType,
25
- data: RefToId<IsData<InstanceType<C>>> | string,
26
- loggers: LoggersType,
27
- autoClassers: AutoUpdateClientManager<any>,
28
- emitter: EventTarget
29
- ): Promise<AutoUpdated<C>> {
30
- if (typeof data !== "string")
31
- processIsRefProperties(data, classParam.prototype, undefined, [], loggers);
32
- const props = Reflect.getMetadata("props", classParam.prototype);
33
- const instance = new (class extends AutoUpdatedClientObject<C> {})(
34
- socket,
35
- data,
36
- loggers,
37
- props,
38
- classParam.name,
39
- classParam,
40
- autoClassers,
41
- emitter
42
- );
43
-
44
- await instance.isLoadedAsync();
45
-
46
- return instance as any;
47
- }
48
-
49
- export abstract class AutoUpdatedClientObject<T extends Constructor<any>> {
50
- protected readonly socket: SocketType;
51
- //protected updates: string[] = [];
52
- protected data: IsData<T>;
53
- protected readonly isServer: boolean = false;
54
- protected readonly loggers: LoggersTypeInternal = {
55
- info: () => {},
56
- debug: () => {},
57
- error: () => {},
58
- warn: () => {},
59
- };
60
- protected isLoading = false;
61
- protected readonly emitter;
62
- protected readonly properties: (keyof T)[];
63
- protected readonly className: string;
64
- protected autoClasser: AutoUpdateManager<any>;
65
- protected isLoadingReferences = false;
66
- public readonly classProp: Constructor<T>;
67
- private readonly EmitterID = new ObjectId().toHexString();
68
- private readonly loadShit = async () => {
69
- if (this.isLoaded()) {
70
- try {
71
- await this.loadForceReferences();
72
- } catch (error) {
73
- this.loggers.error(error);
74
- }
75
- this.isLoadingReferences = false;
76
-
77
- return;
78
- }
79
- this.emitter.addEventListener("loaded" + this.EmitterID, async () => {
80
- try {
81
- await this.loadForceReferences();
82
- } catch (error) {
83
- this.loggers.error(error);
84
- }
85
- this.isLoadingReferences = false;
86
- });
87
- };
88
- constructor(
89
- socket: SocketType,
90
- data: string | RefToId<IsData<T>>,
91
- loggers: LoggersType,
92
- properties: (keyof T)[],
93
- className: string,
94
- classProperty: Constructor<T>,
95
- autoClasser: AutoUpdateManager<any>,
96
- emitter: EventTarget
97
- ) {
98
- this.emitter = emitter;
99
- this.classProp = classProperty;
100
- this.isLoadingReferences = true;
101
- this.isLoading = true;
102
- this.autoClasser = autoClasser;
103
- this.className = className;
104
- this.properties = properties;
105
- this.loggers.debug = loggers.debug;
106
- this.loggers.info = loggers.info;
107
- this.loggers.error = loggers.error;
108
- this.loggers.warn = loggers.warn ?? loggers.info;
109
- this.socket = socket;
110
- if (typeof data === "string") {
111
- if (data === "")
112
- throw new Error(
113
- "Cannot create a new AutoUpdatedClientClass with an empty string for ID."
114
- );
115
- this.socket.emit(
116
- "get" + this.className + data,
117
- null,
118
- (res: ServerResponse<T>) => {
119
- if (!res.success) {
120
- this.isLoading = false;
121
- this.loggers.error("Could not load data from server:", res.message);
122
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
123
- return;
124
- }
125
- checkForMissingRefs<T>(
126
- res.data as any,
127
- properties,
128
- classProperty as any,
129
- autoClasser
130
- );
131
- this.data = res.data as IsData<T>;
132
- this.isLoading = false;
133
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
134
- }
135
- );
136
- this.data = { _id: data } as IsData<T>;
137
- } else {
138
- this.isLoading = true;
139
- checkForMissingRefs<T>(
140
- data as any,
141
- properties,
142
- classProperty as any,
143
- autoClasser
144
- );
145
- this.data = data as any;
146
-
147
- if (this.data._id === "") this.handleNewObject(data as any);
148
- else {this.isLoading = false};
149
- }
150
- if (!this.isServer) this.openSockets();
151
- this.generateSettersAndGetters();
152
- }
153
-
154
- protected handleNewObject(data: IsData<T>) {
155
- this.isLoading = true;
156
- if (!this.className)
157
- throw new Error(
158
- "Cannot create a new AutoUpdatedClientClass without a class name."
159
- );
160
- this.socket.emit("new" + this.className, data, (res: ServerResponse<T>) => {
161
- if (!res.success) {
162
- this.isLoading = false;
163
- this.loggers.error("Could not create data on server:", res.message);
164
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
165
- return;
166
- }
167
- checkForMissingRefs<T>(
168
- res.data as any,
169
- this.properties,
170
- this.classProp as any,
171
- this.autoClasser
172
- );
173
- this.data = res.data as IsData<T>;
174
- this.isLoading = false;
175
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
176
- });
177
- }
178
-
179
- public get extractedData(): {
180
- [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
181
- } {
182
- const extracted = Object.fromEntries(
183
- Object.entries(
184
- processIsRefProperties(this.data, this.classProp.prototype).newData
185
- ).filter(([k, v]) => typeof v !== "function")
186
- );
187
- return structuredClone(extracted) as any as {
188
- [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
189
- };
190
- }
191
-
192
- public isLoaded(): boolean {
193
- return !this.isLoading;
194
- }
195
-
196
- public async isLoadedAsync(): Promise<boolean> {
197
- await this.loadShit();
198
- return this.isLoading
199
- ? new Promise((resolve) => {
200
- this.emitter.addEventListener("loaded" + this.EmitterID, () => {
201
- resolve(this.isLoading === false);
202
- });
203
- })
204
- : true;
205
- }
206
-
207
- private openSockets() {
208
- this.loggers.debug(`[${this.data._id}] Opening socket listeners`);
209
-
210
- this.socket.on(
211
- "update" + this.className + this.data._id,
212
- async (update: ServerUpdateRequest<T>) => {
213
- await this.handleUpdateRequest(update);
214
- }
215
- );
216
- }
217
- // Example server-side handler
218
- private async handleUpdateRequest(
219
- update: ServerUpdateRequest<T>
220
- ): Promise<ServerResponse<undefined>> {
221
- try {
222
- const path = update.key.split(".");
223
- let dataRef: any = this.data;
224
- for (let i = 0; i < path.length - 1; i++) {
225
- if (!dataRef[path[i]]) dataRef[path[i]] = {};
226
- dataRef = dataRef[path[i]];
227
- }
228
- dataRef[path.at(-1)!] = update.value;
229
-
230
- this.loggers.debug(
231
- `[${this.data._id}] Applied patch ${update.key} set to ${update.value}`
232
- );
233
-
234
- // Return success with the applied patch
235
- return { success: true, data: undefined, message: "" };
236
- } catch (error) {
237
- this.loggers.error(`[${this.data._id}] Error applying patch:`, error);
238
- return {
239
- success: false,
240
- message: "Error applying update: " + (error as Error).message,
241
- };
242
- }
243
- }
244
-
245
- private generateSettersAndGetters() {
246
- for (const key of this.properties) {
247
- if (typeof key !== "string") return;
248
-
249
- const k = key as keyof IsData<T>;
250
- const isRef = getMetadataRecursive(
251
- "isRef",
252
- this.classProp.prototype,
253
- key
254
- );
255
-
256
- Object.defineProperty(this, key, {
257
- get: () => {
258
- if (isRef)
259
- return typeof this.data[k] === "string"
260
- ? this.findReference(this.data[k] as string)
261
- : this.data[k];
262
- else return this.data[k];
263
- },
264
- set: () => {
265
- throw new Error(
266
- `Cannot set ${key} this way, use "setValue" function.`
267
- );
268
- },
269
- enumerable: true,
270
- configurable: true,
271
- });
272
- }
273
- }
274
-
275
- protected findReference(id: string): AutoUpdated<any> | undefined {
276
- for (const classer of Object.values(this.autoClasser.classers)) {
277
- const result = classer.getObject(id);
278
- if (result) return result;
279
- }
280
- }
281
-
282
- public async setValue<K extends Paths<InstanceOf<T>>>(
283
- key: K,
284
- val: PathValueOf<T, K>
285
- ): Promise<boolean> {
286
- let value = val as any;
287
- this.loggers.debug(
288
- `[${(this.data as any)._id}] Setting ${key} to ${value}`
289
- );
290
- try {
291
- if (value instanceof AutoUpdatedClientObject)
292
- value = (value as any).extractedData._id;
293
- const path = key.split(".");
294
- let obj = this.data as any;
295
- let lastClass = this as any;
296
- let lastPath = key as string;
297
- for (let i = 0; i < path.length - 1; i++) {
298
- if (
299
- typeof obj[path[i]] !== "object" ||
300
- obj[path[i]] instanceof ObjectId
301
- ) {
302
- let temp = this.resolveReference(
303
- obj[path[i]].toString()
304
- ) as AutoUpdated<any>;
305
- if (!temp) {
306
- return false;
307
- }
308
- lastClass = temp;
309
- lastPath = path.slice(i + 1).join(".");
310
- return await lastClass.setValue(lastPath, value);
311
- } else obj = obj[path[i]];
312
- }
313
-
314
- if (lastClass !== this || lastPath !== (key as any))
315
- throw new Error("???");
316
-
317
- const success = await this.setValueInternal(lastPath, value);
318
-
319
- if (!success) {
320
- return false;
321
- }
322
- const pathArr = lastPath.split(".");
323
- if (pathArr.length === 1) {
324
- (this.data as any)[key as any] = value;
325
- await this.checkAutoStatusChange();
326
- return true;
327
- }
328
- const pathMinusLast = pathArr.splice(0, 1);
329
- let ref = this as any;
330
- for (const p of pathMinusLast) {
331
- ref = ref[p];
332
- }
333
- ref[pathArr.at(-1)!] = value;
334
- await this.checkAutoStatusChange();
335
- return true;
336
- } catch (error) {
337
- this.loggers.error(error);
338
- return false;
339
- }
340
- }
341
-
342
- public getValue(key: Paths<T>) {
343
- let value: any;
344
- for (const part of key.split(".")) {
345
- if (value) value = value[part];
346
- else value = (this.data as any)[part];
347
- }
348
- return value;
349
- }
350
-
351
- protected async setValueInternal(key: string, value: any): Promise<boolean> {
352
- const update: ServerUpdateRequest<T> = this.makeUpdate(key, value);
353
- const promise = new Promise<boolean>((resolve) => {
354
- try {
355
- this.socket.emit(
356
- "update" + this.className + this.data._id,
357
- update,
358
- (res: ServerResponse<T>) => {
359
- resolve(res.success);
360
- }
361
- );
362
- } catch (error) {
363
- this.loggers.error("Error sending update:", error);
364
- resolve(false);
365
- }
366
- });
367
- return promise;
368
- }
369
-
370
- protected makeUpdate(key: string, value: any): any {
371
- const id = this.data._id.toString();
372
- return { _id: id, key, value } as any;
373
- }
374
-
375
- protected async checkAutoStatusChange() {
376
- return;
377
- }
378
-
379
- // return a properly typed AutoUpdatedClientClass (or null)
380
- // inside AutoUpdatedClientClass
381
- protected resolveReference(id: string): AutoUpdatedClientObject<any> | null {
382
- if (!this.autoClasser) throw new Error("No autoClasser");
383
- for (const autoClasser of Object.values(this.autoClasser.classers)) {
384
- const data = autoClasser.getObject(id);
385
- if (data) return data;
386
- }
387
- return null;
388
- }
389
-
390
- private async loadForceReferences(
391
- obj: any = this.data,
392
- proto: any = this.classProp.prototype
393
- ) {
394
- const props: string[] = Reflect.getMetadata("props", proto) || [];
395
-
396
- for (const key of props) {
397
- const isRef = Reflect.getMetadata("isRef", proto, key);
398
-
399
- if (isRef) {
400
- await this.handleLoadOnForced(obj, key);
401
- }
402
-
403
- // If the property itself is a nested object, check deeper
404
- if (obj[key] && typeof obj[key] === "object") {
405
- const nestedProto = Object.getPrototypeOf(obj[key]);
406
- if (nestedProto) {
407
- await this.loadForceReferences(obj[key], nestedProto);
408
- }
409
- }
410
- }
411
- }
412
-
413
- private async handleLoadOnForced(obj: any, key: string) {
414
- if (!this.autoClasser) throw new Error("No autoClassers");
415
- const refId = obj[key];
416
- if (refId) {
417
- for (const classer of Object.values(this.autoClasser.classers)) {
418
- const result = classer.getObject(refId);
419
- if (result) {
420
- obj[key] = result;
421
-
422
- // Recursively load refs inside the resolved object
423
- if (typeof result.loadForceReferences === "function") {
424
- await result.loadForceReferences();
425
- }
426
- break;
427
- }
428
- }
429
- }
430
- }
431
- public async destroy(): Promise<void> {
432
- this.socket.emit("delete" + this.className, this.data._id);
433
- this.wipeSelf();
434
- }
435
-
436
- protected wipeSelf() {
437
- for (const key of Object.keys(this.data)) {
438
- delete (this.data as any)[key];
439
- }
440
- this.loggers.info(`[${this.data._id}] ${this.className} object wiped`);
441
- }
442
- }
443
-
444
- export function processIsRefProperties(
445
- instance: any,
446
- target: any,
447
- prefix: string | null = null,
448
- allProps: string[] = [],
449
- newData = {} as any,
450
- loggers?: LoggersType
451
- ) {
452
- const props: string[] = Reflect.getMetadata("props", target) || [];
453
-
454
- for (const prop of props) {
455
- const path = prefix ? `${prefix}.${prop}` : prop;
456
- allProps.push(path);
457
- newData[prop] = instance[prop];
458
- if (Reflect.getMetadata("isRef", target, prop)) {
459
- (loggers ?? console).debug("Changing isRef:", path);
460
- newData[prop] =
461
- typeof instance[prop] === "string"
462
- ? instance[prop]
463
- : instance[prop]?._id;
464
- }
465
-
466
- const type = Reflect.getMetadata("design:type", target, prop);
467
- if (type?.prototype) {
468
- const nestedProps = Reflect.getMetadata("props", type.prototype);
469
- if (nestedProps && instance[prop]) {
470
- newData[prop] = processIsRefProperties(
471
- instance[prop],
472
- type.prototype,
473
- path,
474
- allProps,
475
- undefined,
476
- loggers
477
- ).newData;
478
- }
479
- }
480
- }
481
- return { allProps, newData };
482
- }
483
-
484
- export function getMetadataRecursive(
485
- metaKey: string,
486
- proto: any,
487
- prop: string
488
- ) {
489
- while (proto) {
490
- const meta = Reflect.getMetadata(metaKey, proto, prop);
491
- if (meta !== undefined) return meta;
492
- proto = Object.getPrototypeOf(proto);
493
- }
494
- return undefined;
495
- }
496
-
497
- function checkForMissingRefs<C extends Constructor<any>>(
498
- data: IsData<InstanceType<C>>,
499
- props: any,
500
- classParam: C,
501
- autoClassers: AutoUpdateManager<any>
502
- ) {
503
- if (typeof data !== "string") {
504
- const entryKeys = Object.keys(data);
505
- for (const prop of props) {
506
- if (
507
- !entryKeys.includes(prop.toString()) &&
508
- getMetadataRecursive("isRef", classParam.prototype, prop.toString())
509
- ) {
510
- findMissingObjectReference(data, prop, autoClassers.classers);
511
- }
512
- }
513
- }
514
- }
515
- function findMissingObjectReference(
516
- data: any,
517
- prop: any,
518
- autoClassers: { [key: string]: AutoUpdateManager<any> }
519
- ) {
520
- for (const ac of Object.values(autoClassers)) {
521
- for (const obj of ac.objectsAsArray) {
522
- const found = Object.values(obj.extractedData).find((value) =>
523
- Array.isArray(value) ? value.includes(data._id) : value === data._id
524
- );
525
- if (found) {
526
- data[prop] = obj._id;
527
- return;
528
- }
529
- }
530
- }
531
- console.log("a");
532
- }
@@ -1,142 +0,0 @@
1
- import { IObjectWithTypegooseFunction } from "@typegoose/typegoose/lib/types.js";
2
- import { Types, Document } from "mongoose";
3
- import { AutoUpdatedClientObject } from "./AutoUpdatedClientObjectClass.js";
4
- import {
5
- AutoProps,
6
- Constructor,
7
- DeRef,
8
- IsData,
9
- LoggersType,
10
- ServerUpdateRequest,
11
- SocketType,
12
- UnboxConstructor,
13
- } from "./CommonTypes.js";
14
- import { AutoUpdateServerManager } from "./AutoUpdateServerManagerClass.js";
15
- import "reflect-metadata";
16
-
17
- export type AutoUpdated<T extends Constructor<any>> = AutoUpdatedServerObject<T> & UnboxConstructor<T>;
18
-
19
- export async function createAutoUpdatedClass<C extends Constructor<any>>(
20
- classParam: C,
21
- socket: SocketType,
22
- data: DocWithProps<InstanceType<C>>,
23
- loggers: LoggersType,
24
- autoClasser: AutoUpdateServerManager<any>,
25
- emitter: EventTarget
26
- ): Promise<AutoProps<C> & AutoUpdated<InstanceType<C>> & DeRef<InstanceType<C>>> {
27
- const instance = new (class extends AutoUpdatedServerObject<
28
- InstanceType<C>
29
- > {})(
30
- socket,
31
- data,
32
- loggers,
33
- Reflect.getMetadata(
34
- "props",
35
- classParam.prototype
36
- ) as (keyof InstanceType<C>)[],
37
- classParam.name,
38
- classParam,
39
- autoClasser,
40
- emitter
41
- );
42
- await instance.isLoadedAsync();
43
- await instance.checkAutoStatusChange();
44
- return instance as AutoProps<C> & AutoUpdated<InstanceType<C>> & DeRef<InstanceType<C>>;
45
- }
46
-
47
- // ---------------------- Class ----------------------
48
- export abstract class AutoUpdatedServerObject<
49
- T extends Constructor<any>
50
- > extends AutoUpdatedClientObject<T> {
51
- protected readonly isServer: boolean = true;
52
- private readonly entry: DocWithProps<T>;
53
- protected override autoClasser: AutoUpdateServerManager<any>;
54
-
55
- constructor(
56
- socket: SocketType,
57
- data: DocWithProps<T>,
58
- loggers: {
59
- info: (...args: any[]) => void;
60
- debug: (...args: any[]) => void;
61
- error: (...args: any[]) => void;
62
- warn?: (...args: any[]) => void;
63
- },
64
- properties: (keyof T)[],
65
- className: string,
66
- classProp: Constructor<T>,
67
- autoClasser: AutoUpdateServerManager<any>,
68
- emitter: EventTarget
69
- ) {
70
- super(
71
- socket,
72
- data.toObject(),
73
- loggers,
74
- properties,
75
- className,
76
- classProp,
77
- autoClasser,
78
- emitter
79
- );
80
- this.autoClasser = autoClasser;
81
- this.entry = data;
82
- }
83
-
84
- protected handleNewObject(_data: IsData<T>) {
85
- throw new Error("Cannot create new objects like this.");
86
- }
87
- protected async setValueInternal(key: string, value: any): Promise<boolean> {
88
- try {
89
- await (
90
- this.autoClasser.classers[this.className] as AutoUpdateServerManager<any>
91
- ).model.updateOne({ _id: this.data._id }, { $set: { [key]: value } });
92
-
93
- const update: ServerUpdateRequest<T> = this.makeUpdate(key, value);
94
- this.socket.emit("update" + this.className + this.data._id, update);
95
-
96
- return true;
97
- } catch (error) {
98
- this.loggers.error("Error saving object:", error);
99
- return false;
100
- }
101
- }
102
-
103
- public async destroy(): Promise<void> {
104
- this.socket.emit("delete" + this.className, this.data._id);
105
- await this.entry.deleteOne({ _id: this.data._id });
106
- this.wipeSelf();
107
- }
108
-
109
- public override async checkAutoStatusChange() {
110
- if (!this.autoClasser.options?.autoStatusDefinitions) return;
111
- const statusPath = this.autoClasser.options.autoStatusDefinitions.statusProperty;
112
- let finalStatus:
113
- | keyof typeof this.autoClasser.options.autoStatusDefinitions.statusEnum
114
- | null = "null";
115
- for (const [currentStatus, statusDef] of Object.entries(
116
- this.autoClasser.options.autoStatusDefinitions.definitions
117
- )) {
118
- finalStatus = currentStatus;
119
- for (const [key, value] of Object.entries(statusDef)) {
120
- if (this.getValue(key as any) !== value) {
121
- finalStatus = null;
122
- break;
123
- }
124
- }
125
-
126
- if (!finalStatus) continue;
127
- if(this.autoClasser.options.autoStatusDefinitions.statusEnum[finalStatus] === this.getValue(statusPath as any)) break;
128
- await this.setValue(
129
- statusPath as any,
130
- this.autoClasser.options.autoStatusDefinitions.statusEnum[finalStatus] as any
131
- );
132
- break;
133
- }
134
- if (!finalStatus)
135
- throw new Error(`No final status found`);
136
- }
137
-
138
- }
139
-
140
- export type DocWithProps<T> = Document &
141
- Omit<T & { _id: Types.ObjectId; __v: number }, "typegooseName"> &
142
- IObjectWithTypegooseFunction;