@hiki9/rich-domain
Version:
Rich Domain is a library that provides a set of tools to help you build complex business logic in NodeJS using Domain Driven Design principles.
78 lines • 3.2 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueObject = void 0;
const lodash_1 = __importDefault(require("lodash"));
const deep_freeze_1 = require("../../utils/deep-freeze");
const auto_mapper_value_object_1 = require("./auto-mapper-value-object");
const revalidate_error_1 = require("./revalidate-error");
class ValueObject {
constructor(input) {
this.isValueObject = true;
const instance = this.constructor;
const props = typeof instance?.hooks?.transformBeforeCreate === 'function'
? instance.hooks.transformBeforeCreate(input)
: input;
this.props = (0, deep_freeze_1.deepFreeze)(props);
this.revalidate();
}
get value() {
return this.props;
}
getRawProps() {
return this.props;
}
toPrimitives() {
const result = ValueObject.autoMapper.valueObjectToObj(this);
const frozen = (0, deep_freeze_1.deepFreeze)(result);
return frozen;
}
isEqual(other) {
if (!other)
return false;
if (!(other instanceof ValueObject))
return false;
if (this === other)
return true;
const currentProps = lodash_1.default.cloneDeep(this.props);
const providedProps = lodash_1.default.cloneDeep(other.props);
return lodash_1.default.isEqual(currentProps, providedProps);
}
clone() {
const instance = Reflect.getPrototypeOf(this);
const args = [this.props];
const obj = Reflect.construct(instance.constructor, args);
return obj;
}
revalidate() {
const instance = this.constructor;
if (instance?.hooks?.typeValidation) {
if (typeof instance.hooks.typeValidation !== 'object') {
const value = this.props;
const errorMessage = instance.hooks.typeValidation(value);
if (errorMessage) {
const expected = instance.hooks.typeValidation?.name;
const fieldMessage = `. field=${expected}(primitive) instance=${instance?.name}`;
throw (0, revalidate_error_1.RevalidateError)(errorMessage + fieldMessage, value, expected);
}
}
else {
Object.entries(instance.hooks.typeValidation)
.forEach(([key, validation]) => {
const value = this.props[key];
const errorMessage = validation(value);
if (errorMessage) {
const fieldMessage = `. field=${key?.toString()} instance=${instance?.name}`;
throw (0, revalidate_error_1.RevalidateError)(errorMessage + fieldMessage, value, validation.name);
}
});
}
}
instance?.hooks?.rules?.(this.props);
}
}
exports.ValueObject = ValueObject;
ValueObject.autoMapper = new auto_mapper_value_object_1.AutoMapperValueObject();
//# sourceMappingURL=value-object.js.map