octonom
Version:
Object Document Mapper for any database
61 lines • 2.74 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../errors");
const schema_1 = require("./schema");
class NumberSchema {
constructor(options = {}) {
this.options = options;
}
create(value, sanitizeOptions = {}) {
const sanitizedValue = this.sanitize(value, sanitizeOptions);
if (sanitizedValue === undefined) {
return undefined;
}
return {
parent: sanitizeOptions.parent,
schema: this,
value: this.sanitize(value, sanitizeOptions),
};
}
toObject(instance) {
return instance.value;
}
validate(instance) {
return __awaiter(this, void 0, void 0, function* () {
if (this.options.integer && !Number.isInteger(instance.value)) {
throw new errors_1.ValidationError('Number is not an integer.', 'no-integer', instance.parent);
}
if (this.options.min !== undefined && instance.value < this.options.min) {
throw new errors_1.ValidationError(`Number must not be less than ${this.options.min}.`, 'number-min', instance.parent);
}
if (this.options.max !== undefined && instance.value > this.options.max) {
throw new errors_1.ValidationError(`Number must not be greater than ${this.options.max}.`, 'number-max', instance.parent);
}
yield schema_1.validate(this.options, instance);
});
}
sanitize(value, sanitizeOptions = {}) {
if (value === undefined && sanitizeOptions.defaults) {
return typeof this.options.default === 'function'
? this.options.default()
: this.options.default;
}
if (value === undefined) {
return undefined;
}
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new errors_1.SanitizationError('Value is not a number.', 'no-number', sanitizeOptions.parent);
}
return value;
}
}
exports.NumberSchema = NumberSchema;
//# sourceMappingURL=number.js.map