UNPKG

@cheetah.js/orm

Version:
100 lines 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueObject = void 0; const core_1 = require("@cheetah.js/core"); class ValueObject { constructor(value, skipValidation = false) { if (!skipValidation && (!this.validate(value) || !this.validateDatabase(value))) { throw new core_1.HttpException(`Invalid value for ${this.constructor.name}`, 400); } this.setValue(value); } /** * Creates a Value Object instance from a value. * * @example * Email.from('test@test.com'); * * @param value */ static from(value) { return new this(value); } /** * Returns the scalar value of the Value Object. * */ getValue() { return this.value; } /** * Compares the value of the Value Object with another Value Object. * * @param vo */ equals(vo) { return this.getValue() === vo.getValue(); } /** * Returns the database settings of the Value Object. * * @returns */ getDatabaseValues() { return { max: this.max, min: this.min, precision: this.precision, scale: this.scale, }; } /** * Sets the value of the Value Object. * * @param value * @private */ setValue(value) { this.value = value; } /** * Validates the value of the Value Object. * It is private so that it can only be called by the constructor. * * @param value * @returns */ validateDatabase(value) { if (typeof value === "string") { if (this.max !== undefined && value.length > this.max) { throw new core_1.HttpException(`Value exceeds maximum length of ${this.max}`, 400); } if (this.min !== undefined && value.length < this.min) { throw new core_1.HttpException(`Value is less than minimum length of ${this.min}`, 400); } } else if (typeof value === "number") { if (this.max !== undefined && value > this.max) { throw new core_1.HttpException(`Value exceeds maximum value of ${this.max}`, 400); } if (this.min !== undefined && value < this.min) { throw new core_1.HttpException(`Value is less than minimum value of ${this.min}`, 400); } if (this.precision !== undefined) { const totalDigits = value.toString().replace(".", "").length; if (totalDigits > this.precision) { throw new core_1.HttpException(`Value exceeds precision of ${this.precision}`, 400); } } if (this.scale !== undefined) { const decimalDigits = (value.toString().split(".")[1] || "").length; if (decimalDigits > this.scale) { throw new core_1.HttpException(`Value exceeds scale of ${this.scale}`, 400); } } } return true; } } exports.ValueObject = ValueObject; //# sourceMappingURL=value-object.js.map