import { EntityId } from './EntityId'; import {createSnapshot} from "./helpers"; const isEntity = >(v: Entity): v is Entity => { return v instanceof Entity } export abstract class Entity> { protected readonly _id: H; protected props: T; protected _snapshot: string; snapshot(): T { // важливо: snapshot має бути стабільним (createSnapshot) const snapObj = createSnapshot(this.props); this._snapshot = JSON.stringify(snapObj); const copy = JSON.parse(this._snapshot) as T; Object.freeze(copy); return copy; } isDirty(): boolean { if (!this._snapshot) { return false; } return this._snapshot !== JSON.stringify(createSnapshot(this.props)); } protected constructor(props: T, id?: H|E) { if (id) { this._id = (typeof id === 'object' ? id : new EntityId(id)); } else { this._id = (new EntityId()); } this.props = props } public equals(object?: Entity): boolean { if (object === null || object === undefined) { return false } if (this === object) { return true } if (!isEntity(object)) { return false } return this._id.equals(object._id); } get id(): H { return this._id } toPrimitive(): T { return this.props } // eslint-disable-next-line @typescript-eslint/no-explicit-any toJSON(): any { return this.toPrimitive(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any toSnapshot(): any { return this.toPrimitive(); } }