validata
Version:
Type safe data validation and sanitization
82 lines • 3.61 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeAsArray = exports.asArray = exports.maybeArray = exports.isArray = void 0;
const common_1 = require("./common");
const types_1 = require("./types");
class Generic {
constructor() {
this.check = (value) => {
return Array.isArray(value);
};
this.convert = (value) => {
return this.check(value) ? value : [value];
};
this.process = (check, target, path) => {
const issues = [];
const output = [];
target.forEach((value, i) => {
const childResult = check.process(value, [...path, i]);
if ((0, types_1.isIssue)(childResult)) {
issues.push(...childResult.issues);
return;
}
if (childResult) {
output.push(childResult.value);
}
else {
output.push(value);
}
});
return issues.length ? { issues } : { value: output };
};
this.coerce = (options) => (next) => (value, path) => {
if (!options)
return next(value, path);
let coerced = value;
if (options.coerceMaxLength !== undefined && coerced.length > options.coerceMaxLength) {
coerced = coerced.slice(0, options.coerceMaxLength);
}
if (options.item) {
const result = this.process(options.item, coerced, path);
if ((0, types_1.isIssue)(result)) {
return result;
}
if (result) {
coerced = result.value;
}
}
return next(coerced, path);
};
this.validate = (value, path, options) => {
const result = (0, common_1.basicValidation)(value, path, options);
if (options.minLength !== undefined && value.length < options.minLength) {
result.issues.push(types_1.Issue.forPath(path, value, 'min-length', { length: value.length, min: options.minLength }));
}
if (options.maxLength !== undefined && value.length > options.maxLength) {
result.issues.push(types_1.Issue.forPath(path, value, 'max-length', { length: value.length, max: options.maxLength }));
}
return result;
};
}
}
const isArray = (item, options) => {
const generic = new Generic();
return (0, common_1.createIsCheck)('array', generic.check, generic.coerce, generic.validate)(Object.assign(Object.assign({}, options), { item }));
};
exports.isArray = isArray;
const maybeArray = (item, options) => {
const generic = new Generic();
return (0, common_1.createMaybeCheck)('array', generic.check, generic.coerce, generic.validate)(Object.assign(Object.assign({}, options), { item }));
};
exports.maybeArray = maybeArray;
const asArray = (item, options) => {
const generic = new Generic();
return (0, common_1.createAsCheck)('array', generic.check, generic.convert, generic.coerce, generic.validate)(Object.assign(Object.assign({}, options), { item }));
};
exports.asArray = asArray;
const maybeAsArray = (item, options) => {
const generic = new Generic();
return (0, common_1.createMaybeAsCheck)('array', generic.check, generic.convert, generic.coerce, generic.validate)(Object.assign(Object.assign({}, options), { item }));
};
exports.maybeAsArray = maybeAsArray;
//# sourceMappingURL=array.js.map
;