diff --git a/orm.d.ts b/orm.d.ts index 60ab6d6..cbdb036 100644 --- a/orm.d.ts +++ b/orm.d.ts @@ -26,6 +26,20 @@ export declare abstract class Entity { /** @public */ export declare type EntityConstructor = new (data?: T) => Entity; +/** @public */ +export declare class EntityManager { + private readonly _storage; + private _saveMap; + private _removeMap; + constructor(storage: Storage_2); + persist(entity: Entity): this; + persistMany(entities: Entity[]): this; + remove(entity: Entity): this; + forget(): this; + flush(): Promise; + refresh(entity: Entity): Promise>; +} + /** @public */ export declare class ErrEntityHasNoUniqKeyValue extends Error { } diff --git a/src/app/entity/manager.ts b/src/app/entity/manager.ts new file mode 100644 index 0000000..ce53d18 --- /dev/null +++ b/src/app/entity/manager.ts @@ -0,0 +1,64 @@ +import { Entity } from '../entity' +import { Storage } from '../storage' + +/** @public */ +export class EntityManager { + private readonly _storage: Storage + private _saveMap: Map> + private _removeMap: Map> + + constructor(storage: Storage) { + this._storage = storage + this._saveMap = new Map() + this._removeMap = new Map() + } + + persist(entity: Entity): this { + const key = [entity.constructor.name, entity.getUniqKey()].join('&') + this._saveMap.set(key, entity) + return this + } + + persistMany(entities: Entity[]): this { + for (let entity of entities) { + this.persist(entity) + } + return this + } + + remove(entity: Entity): this { + const key = [entity.constructor.name, entity.getUniqKey()].join('&') + this._removeMap.set(key, entity) + return this + } + + forget(): this { + this._saveMap = new Map() + return this + } + + async flush() { + if (!this._saveMap.size && !this._removeMap.size) return this + + const session = this._storage.createSession() + await session.start() + await session.commit(async () => { + for (let en of this._saveMap.values()) { + await en._getRepo(this._storage).save(en) + } + this._saveMap = new Map() + + for (let en of this._removeMap.values()) { + await en._getRepo(this._storage).remove(en) + } + this._removeMap = new Map() + }) + + return this + } + + async refresh(entity: Entity) { + const repo = entity._getRepo(this._storage) + return repo.findById(entity.getUniqKey()) + } +} diff --git a/src/index.ts b/src/index.ts index 1ea4a00..591e903 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,3 +6,4 @@ export { Data, ValuesObject } from './app/data' export { Entity, EntityConstructor, ErrEntityHasNoUniqKeyValue } from './app/entity' export { Repo, ErrFoundNotUniqEntity, ErrEntityNotFound } from './app/repo' export { Storage, StorageCursor, ErrStorage, ErrNoSession, StorageSession } from './app/storage' +export { EntityManager } from './app/entity/manager'