UNPKG

@prismicio/types-internal

Version:
33 lines (29 loc) 785 B
import { chain } from "fp-ts/Either" import { pipe } from "fp-ts/function" import * as t from "io-ts" export type IntFromPixelsC = t.Type<t.Int, string, unknown> const PixelsRegex = /^([0-9]+)px$/ /** * A codec that succeeds if a string representing pixels (eg: "200px") can be * parsed to an integer */ export default new t.Type<t.Int, string, unknown>( "IntFromPixels", t.Int.is, (u, c) => pipe( t.string.validate(u, c), chain((strPixels) => { try { const matched = strPixels.match(PixelsRegex) if (!matched) return t.failure(u, c) /* eslint-disable @typescript-eslint/no-non-null-assertion */ const parsed = parseInt(matched[1]!) as t.Int return t.success(parsed) } catch { return t.failure(u, c) } }), ), String, )