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

36 lines
802 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> {
2025-01-30 09:24:08 +00:00
protected readonly _value: T;
2025-01-29 19:02:59 +00:00
protected constructor(value: T) {
2025-01-30 09:24:08 +00:00
this._value = typeof value === "object" && value !== null ? Object.freeze(value) : value;
2025-01-29 19:02:59 +00:00
Object.freeze(this);
}
equals(other: ValueObject<T>): boolean {
if (!(other instanceof ValueObject)) {
return false;
}
2025-01-30 09:24:08 +00:00
if (other._value === undefined || other._value === null) {
2025-01-29 19:02:59 +00:00
return false;
}
2025-01-30 09:24:08 +00:00
return shallowEqual(this._value, other._value);
2025-01-29 19:02:59 +00:00
}
getValue(): T {
2025-01-30 09:24:08 +00:00
return this._value;
2025-01-29 19:02:59 +00:00
}
2025-01-30 09:24:08 +00:00
isEmpty(): boolean {
return this._value === null || this._value === undefined;
2025-01-29 19:02:59 +00:00
}
2025-01-30 09:24:08 +00:00
toString(): string {
return this._value !== null && this._value !== undefined ? String(this._value) : "";
2025-01-29 19:02:59 +00:00
}
}