ivanovna.orm/src/app/entity.ts

58 lines
1.2 KiB
TypeScript

import { Data } from './data'
import { Repo } from './repo'
import { Storage } from './storage'
/** @public */
export type EntityConstructor<T extends Data> = new (data?: T) => Entity<T>
/** @public */
export class ErrEntityHasNoUniqKeyValue extends Error {}
/** @public */
export abstract class Entity<T extends Data> {
abstract _getRepo(storage: Storage): Repo<Entity<T>>
abstract _getVO(): T
protected _data: T
private __id = '' // Storage inner id
get data(): T {
return this._data
}
get _id(): string {
return this.__id
}
set _id(value: string) {
this.__id = value
}
constructor(data?: T) {
if (data) {
const newData = this._getVO()
newData.fromObject(data.toObject(['_id']))
this._data = newData
} else {
this._data = this._getVO()
}
}
getUniqKey(): any {
const id = this._data[this._data.uniqKey()]
if (id === null || id === undefined || id === '') {
throw new ErrEntityHasNoUniqKeyValue()
} else {
return id
}
}
isPersisted(): boolean {
return this.__id !== ''
}
toString() {
return this.getUniqKey()
}
}