feat: LazyEntityUpdater

This commit is contained in:
2024-03-09 04:50:55 +00:00
parent a38f72fa46
commit fa29486af6
8 changed files with 126 additions and 42 deletions
@@ -0,0 +1,31 @@
import type { IResourceController, ValidEntity, ValidEntityType } from "./ResourceController.js";
export abstract class LazyEntityUpdater<Entity extends ValidEntity>{
protected abstract readonly _indirectNames: (keyof Entity)[];
protected abstract readonly _entityType: ValidEntityType<Entity>;
protected abstract readonly _raw: Entity;
protected abstract readonly resourceController: IResourceController;
public get raw(): Readonly<Entity> {
return this._raw;
}
public get entityType(): ValidEntityType<Entity> {
return this._entityType;
}
public update(callback: (oldRaw: Entity) => void, force = false) {
const oldRaw = { ...this._raw };
callback(this._raw);
if (!force) {
for (const indirectName of this._indirectNames) {
if (oldRaw[indirectName] !== this._raw[indirectName]) {
throw new Error(`${String(indirectName)} change by update() is not allowed`);
}
}
}
this.resourceController.setDirty(this);
}
}