validata
Version:
Type safe data validation and sanitization
66 lines • 2.63 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeTuple = exports.isTuple = void 0;
const common_1 = require("./common");
const types_1 = require("./types");
class Generic {
constructor() {
this.check = (value) => {
return Array.isArray(value);
};
this.process = (check, target, path) => {
const issues = [];
const output = [];
check.forEach((c, i) => {
if (i >= target.length) {
issues.push(types_1.Issue.forPath(i, undefined, 'expected-item'));
return;
}
const value = i < target.length ? target[i] : undefined;
const childResult = c.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);
}
});
if (target.length > check.length) {
for (let i = check.length; i < target.length; i++) {
const value = target[i];
issues.push(types_1.Issue.forPath(i, value, 'unexpected-item'));
}
}
return issues.length ? { issues } : { value: output };
};
this.coerce = (options) => (next) => (value, path) => {
if (!options)
return next(value, path);
let coerced = value;
const result = this.process(options.items, coerced, path);
if ((0, types_1.isIssue)(result)) {
return result;
}
if (result) {
coerced = result.value;
}
return next(coerced, path);
};
this.validate = (value, path, options) => (0, common_1.basicValidation)(value, path, options);
}
}
const isTuple = (items, options) => {
const generic = new Generic();
return (0, common_1.createIsCheck)('tuple', generic.check, generic.coerce, generic.validate)(Object.assign(Object.assign({}, options), { items }));
};
exports.isTuple = isTuple;
const maybeTuple = (items, options) => {
const generic = new Generic();
return (0, common_1.createMaybeCheck)('tuple', generic.check, generic.coerce, generic.validate)(Object.assign(Object.assign({}, options), { items }));
};
exports.maybeTuple = maybeTuple;
//# sourceMappingURL=tuple.js.map
;