import * as t from 'io-ts' import {RichError, funcLabel} from './util' import * as Either from 'fp-ts/lib/Either' import {pipe} from 'fp-ts/lib/pipeable' export type Decoder = Omit, 'encode'> // prettier-ignore interface Mapper { >(from: t.Type, to: t.Type, map: (f: From) => ToO): Decoder & {from: From; to: ToA}; >(from: t.Type, to: t.Type, map: (f: From) => ToO, unmap: (t: ToA) => From): t.Type & {from: From; to: ToA}; } /** * A helper for building "parser-decoder" types - that is, types that validate an input, * transform it into another type, and then validate the target type. * * @example * const StringsFromMixedArray = mapper( * t.array(t.any), * t.array(t.string), * mixedArray => mixedArray.filter(value => typeof value === 'string') * ) * StringsFromMixedArray.decode(['a', 1, 'b', 2]) // right(['a', 'b']) * StringsFromMixedArray.decode('not an array') // left(...) * * @see parser * * @param from the expected type of input value * @param to the expected type of the decoded value * @param map transform (decode) a `from` type to a `to` type * @param unmap transfrom a `to` type back to a `from` type */ export const mapper: Mapper = ( from: t.Type, to: t.Type, map: (f: From) => To, unmap: (t: To) => From = RichError.thrower('unmapper/encoder not implemented') ) => { const fail = (s: From, c: t.Context, info: string) => t.failure(s, c.concat([{key: `decoder [${funcLabel(map)}]: ${info}`, type: to}])) const piped = from.pipe( new t.Type( to.name, to.is, (s, c) => pipe( Either.tryCatch( () => map(s), err => `error thrown decoding: [${err}]` ), Either.fold( e => fail(s, c, e), value => to.validate(value, c) ) ), unmap ), `${from.name} |> ${funcLabel(map)} |> ${to.name}` ) as any return Object.assign(piped, {from, to}) } /** * A helper for parsing strings into other types. A wrapper around `mapper` where the `from` type is `t.string`. * @see mapper * * @example * const IntFromString = parser(t.Int, parseFloat) * IntFromString.decode('123') // right(123) * IntFromString.decode('123.4') // left(...) * IntFromString.decode('not a number') // left(...) * IntFromString.decode(123) // left(...) * * @param type the target type * @param decode transform a string into the target type * @param encode transform the target type back into a string */ export const parser = >( type: t.Type, decode: (value: string) => ToO, encode: (value: ToA) => string = String ): t.Type & {from: string; to: ToA} => mapper(t.string, type, decode, encode)