validata
Version:
Type safe data validation and sanitization
72 lines • 2.81 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeAsEnum = exports.asEnum = exports.maybeEnum = exports.isEnum = void 0;
const common_1 = require("./common");
const types_1 = require("./types");
class Generic {
constructor(type) {
this.keyToValue = {};
this.valueToKey = {};
this.check = (expectInEnum = false) => {
return (value) => {
return expectInEnum
? value in this.valueToKey
: (typeof value === 'string' || typeof value === 'number');
};
};
this.coerce = () => (next) => (value, path) => {
return next(value, path);
};
this.convert = (value) => {
if (value in this.keyToValue) {
return this.keyToValue[value];
}
return undefined;
};
this.validate = (value, path, options) => {
const result = (0, common_1.basicValidation)(value, path, options);
if (!(value in this.valueToKey)) {
const info = {};
if (options.showValidKeys) {
info.validKeys = Object.values(this.keyToValue);
}
if (options.showValidValues) {
info.validValues = Object.keys(this.keyToValue);
}
result.issues.push(types_1.Issue.forPath(path, value, 'key-not-found', info));
}
return result;
};
this.isNumber = (key) => {
return /^\d+$/gi.test(key);
};
for (const key in type) {
if (!key || this.isNumber(key)) {
continue;
}
this.keyToValue[key] = type[key];
this.valueToKey[type[key]] = key;
}
}
}
const isEnum = (type, options = {}) => {
const g = new Generic(type);
return (0, common_1.createIsCheck)('enum', g.check(), g.coerce, g.validate)(Object.assign({}, options));
};
exports.isEnum = isEnum;
const maybeEnum = (type, options = {}) => {
const g = new Generic(type);
return (0, common_1.createMaybeCheck)('enum', g.check(), g.coerce, g.validate)(Object.assign({}, options));
};
exports.maybeEnum = maybeEnum;
const asEnum = (type, options = {}) => {
const g = new Generic(type);
return (0, common_1.createAsCheck)('enum', g.check(true), g.convert, g.coerce, g.validate)(Object.assign({}, options));
};
exports.asEnum = asEnum;
const maybeAsEnum = (type, options = {}) => {
const g = new Generic(type);
return (0, common_1.createMaybeAsCheck)('enum', g.check(true), g.convert, g.coerce, g.validate)(Object.assign(Object.assign({}, options), { strictParsing: true }));
};
exports.maybeAsEnum = maybeAsEnum;
//# sourceMappingURL=enum.js.map
;