import { Database } from '../Database'; import { InstantReaction } from '../register/InstantReaction'; export class Reactive { private target: any; private instantReaction: InstantReaction | null = null; private entityName: string | null = null; private db: Database | null = null; private constructor(target: T, entityName: string) { this.target = target; this.instantReaction = InstantReaction.getInstance(); this.entityName = entityName; this.db = Database.getInstance(); } private getter(target: any, p: string | symbol) { return target[p]; } private setter(target: any, p: string | symbol, newValue: any): boolean { if (!this.instantReaction) { throw new Error('InstantReaction not found'); } if (newValue !== this.target[p]) { target[p] = newValue; this.instantReaction._reactions.forEach((reaction) => reaction()); this.db!.insertOrUpdate(this.entityName!, target, p, newValue); return true; } return true; } public static create(target: T, entityName: string): T { const reactiveInstance = new Reactive(target, entityName); return new Proxy(target, { get: reactiveInstance.getter.bind(reactiveInstance), set: reactiveInstance.setter.bind(reactiveInstance), }) as T; } public static array(data: any[], entityName: string) { return data.map((item) => this.create(item, entityName)); } }