Uecko_ERP/packages/rdx-ddd/src/domain-entity.ts

42 lines
980 B
TypeScript
Raw Normal View History

2025-05-09 10:45:32 +00:00
import { UniqueID } from "./value-objects";
2025-02-01 21:48:13 +00:00
export abstract class DomainEntity<T extends object> {
2026-03-09 20:23:48 +00:00
private _props: T;
2025-02-20 18:55:24 +00:00
public readonly id: UniqueID;
2025-02-01 21:48:13 +00:00
protected constructor(props: T, id?: UniqueID) {
2026-03-09 20:23:48 +00:00
this.id = id ?? UniqueID.generateNewID();
this._props = props;
}
protected get props(): T {
return this._props;
}
protected set props(value: T) {
this._props = value;
2025-02-01 21:48:13 +00:00
}
protected _flattenProps(props: T): { [s: string]: any } {
return Object.entries(props).reduce((result: any, [key, valueObject]) => {
result[key] = valueObject.value;
return result;
}, {});
}
2026-03-09 20:23:48 +00:00
equals(other?: DomainEntity<T>): boolean {
if (!other) return false;
2025-02-01 21:48:13 +00:00
return other instanceof DomainEntity && this.id.equals(other.id);
}
toString(): { [s: string]: string } {
2025-02-20 18:55:24 +00:00
const flattenProps = this._flattenProps(this.props);
2025-02-01 21:48:13 +00:00
return {
2025-02-20 18:55:24 +00:00
id: this.id.toString(),
2025-02-01 21:48:13 +00:00
...flattenProps.map((prop: any) => String(prop)),
};
}
}