io-ts-extra
Version:
Adds pattern matching, optional properties, and several other helpers and types, to io-ts.
36 lines • 1.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRightUnsafe = exports.validationErrors = void 0;
const util_1 = require("util");
const os_1 = require("os");
/**
* Similar to io-ts's PathReporter, but gives slightly less verbose output.
* @param validation Usually the result of calling `.decode` with an io-ts codec.
* @param typeAlias io-ts type names can be verbose. If the type you're using doesn't have a name,
* you can use this to keep error messages shorter.
*/
const validationErrors = (validation, typeAlias) => {
if (validation._tag === 'Right') {
return ['No errors!'];
}
return validation.left.map(e => {
var _a;
const name = typeAlias || ((_a = e.context[0]) === null || _a === void 0 ? void 0 : _a.type.name);
const lastType = e.context.length && e.context[e.context.length - 1].type.name;
const path = name + e.context.map(c => c.key).join('.');
return `Invalid value {${util_1.inspect(e.value)}} supplied to ${path}. Expected ${lastType}.`;
});
};
exports.validationErrors = validationErrors;
/**
* Either returns the `.right` of a io-ts `Validation`, or throws with a report of the validation error.
* @see validationErrors
*/
const getRightUnsafe = (validation, typeAlias) => {
if (validation._tag === 'Right') {
return validation.right;
}
throw Error(exports.validationErrors(validation, typeAlias).join(os_1.EOL));
};
exports.getRightUnsafe = getRightUnsafe;
//# sourceMappingURL=reporters.js.map