ts-cast
Version:
Runtime typechecking
25 lines (24 loc) • 987 B
JavaScript
import { withName } from '../helpers/names';
const isNonEmpty = (value) => value.length > 0;
const success = (result) => ({ ok: true, result, errors: [] });
const failure = (errors) => ({ ok: false, result: undefined, errors });
export const validate = (casterFn) => (value, context) => {
const errors = [];
const reportError = (message, ctx) => {
errors.push({ message, context: ctx });
};
try {
const result = casterFn(value, context, reportError);
return isNonEmpty(errors) ? failure(errors) : success(result);
}
catch (err) {
return failure([{ message: err.message, context }]);
}
};
export const validation = (casterFn, invalidFactory, validFactory) => {
const validator = validate(casterFn);
return withName((value, context) => {
const vResult = validator(value, context);
return vResult.ok ? validFactory(vResult.result) : invalidFactory(vResult.errors);
}, `validation<*, ${casterFn}>`);
};