jaywalk
Version:
Runtime type validation
88 lines • 3.1 kB
JavaScript
;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var any_1 = require('./any');
var utils_1 = require('../utils');
var String = (function (_super) {
__extends(String, _super);
function String(options) {
if (options === void 0) { options = {}; }
_super.call(this, options);
this.type = 'String';
if (options.minLength != null) {
this.minLength = options.minLength;
}
if (options.maxLength != null) {
this.maxLength = options.maxLength;
}
if (options.pattern != null) {
this.pattern = options.pattern;
}
this._tests.push(isString);
this._tests.push(toPatternTest(this.pattern));
this._tests.push(toMinLengthTest(this.minLength));
this._tests.push(toMaxLengthTest(this.maxLength));
}
String.prototype._isType = function (value, path, context) {
return utils_1.wrapIsType(this, value, path, context, _super.prototype._isType, function (value) {
if (typeof value === 'string') {
return 1;
}
throw context.error(path, 'String', 'type', 'String', value);
});
};
String.prototype._extend = function (options) {
return _super.prototype._extend.call(this, options);
};
return String;
}(any_1.Any));
exports.String = String;
function isString(value, path, context, next) {
if (typeof value !== 'string') {
throw context.error(path, 'String', 'type', 'String', value);
}
return next(value);
}
function toMinLengthTest(minLength) {
if (minLength == null) {
return utils_1.toNext;
}
var minLengthValue = utils_1.toValue(minLength);
return function (value, path, context, next) {
var minLength = minLengthValue(path, context);
if (Buffer.byteLength(value) < minLength) {
throw context.error(path, 'String', 'minLength', minLength, value);
}
return next(value);
};
}
function toMaxLengthTest(maxLength) {
if (maxLength == null) {
return utils_1.toNext;
}
var maxLengthValue = utils_1.toValue(maxLength);
return function (value, path, context, next) {
var maxLength = maxLengthValue(path, context);
if (Buffer.byteLength(value) > maxLength) {
throw context.error(path, 'String', 'maxLength', maxLength, value);
}
return next(value);
};
}
function toPatternTest(pattern) {
if (pattern == null) {
return utils_1.toNext;
}
var patternValue = utils_1.toValue(pattern);
return function (value, path, context, next) {
var re = new RegExp(patternValue(path, context));
if (!re.test(value)) {
throw context.error(path, 'String', 'pattern', pattern, value);
}
return next(value);
};
}
//# sourceMappingURL=string.js.map