octonom
Version:
Object Document Mapper for any database
74 lines • 3.42 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 StringSchema {
constructor(options = {}) {
this.options = options;
}
create(value, sanitizeOptions = {}) {
const sanitizedValue = this.sanitize(value, sanitizeOptions);
if (sanitizedValue === undefined) {
return undefined;
}
return {
value: sanitizedValue,
schema: this,
parent: sanitizeOptions.parent,
};
}
toObject(instance) {
return instance.value;
}
validate(instance) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: remove?
if (instance.value === undefined) {
if (this.options.required) {
throw new errors_1.ValidationError('Required value is undefined.', 'no-string', instance.parent);
}
return;
}
if (typeof instance.value !== 'string') {
throw new errors_1.ValidationError('Value is not a string.', 'no-string', instance.parent);
}
if (this.options.enum && this.options.enum.indexOf(instance.value) === -1) {
throw new errors_1.ValidationError(`String not in enum: ${this.options.enum.join(', ')}.`, 'string-enum', instance.parent);
}
if (this.options.min && instance.value.length < this.options.min) {
throw new errors_1.ValidationError(`String must not have less than ${this.options.min} characters.`, 'string-min', instance.parent);
}
if (this.options.max && instance.value.length > this.options.max) {
throw new errors_1.ValidationError(`String must not have more than ${this.options.max} characters.`, 'string-max', instance.parent);
}
if (this.options.regex && !this.options.regex.test(instance.value)) {
throw new errors_1.ValidationError(`String does not match regex.`, 'string-regex', 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 !== 'string') {
throw new errors_1.SanitizationError('Value is not a string.', 'no-string', sanitizeOptions.parent);
}
return value;
}
}
exports.StringSchema = StringSchema;
//# sourceMappingURL=string.js.map