UNPKG

io-ts-types

Version:

A collection of codecs and combinators for use with io-ts

35 lines (34 loc) 1.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withMessage = void 0; var withValidate_1 = require("./withValidate"); var Either_1 = require("fp-ts/lib/Either"); /** * Returns a clone of the given codec that sets the given string as error messsage * * @example * import { withMessage } from 'io-ts-types/lib/withMessage' * import * as t from 'io-ts' * import { PathReporter } from 'io-ts/lib/PathReporter' * import { right } from 'fp-ts/lib/Either' * * const T = withMessage(t.number, () => 'Invalid number') * * assert.deepStrictEqual(T.decode(1), right(1)) * assert.deepStrictEqual(PathReporter.report(T.decode(null)), ['Invalid number']) * * @since 0.4.3 */ function withMessage(codec, message) { return withValidate_1.withValidate(codec, function (i, c) { return Either_1.mapLeft(function () { return [ { value: i, context: c, message: message(i, c), actual: i } ]; })(codec.validate(i, c)); }); } exports.withMessage = withMessage;