Uecko_ERP/apps/server/src/common/domain/value-object.ts

39 lines
787 B
TypeScript
Raw Normal View History

2025-01-29 19:02:59 +00:00
import { shallowEqual } from "shallow-equal-object";
export abstract class ValueObject<T> {
protected readonly value: T;
protected constructor(value: T) {
if (value === null || value === undefined) {
throw new Error("ValueObject value cannot be null or undefined");
}
this.value = typeof value === "object" ? Object.freeze(value) : value;
Object.freeze(this);
}
equals(other: ValueObject<T>): boolean {
if (!(other instanceof ValueObject)) {
return false;
}
if (other.value === undefined) {
return false;
}
return shallowEqual(this.value, other.value);
}
getValue(): T {
return this.value;
}
toString(): string {
return String(this.value);
}
clone(): this {
return Object.create(this);
}
}