gcanti / io-ts-types

A collection of codecs and combinators for use with io-ts
https://gcanti.github.io/io-ts-types/
MIT License
311 stars 40 forks source link

Refactor createOptionFromJSON and createEitherFromJSON #79

Closed gcanti closed 5 years ago

gcanti commented 5 years ago

createOptionFromJSON should handle the following encoding

type JSONOption<A> = { _tag: 'None' } | { _tag: 'Some'; value: A }

createEitherFromJSON should handle the following encoding

type JSONEither<L, A> = { _tag: 'left', value: L } | { _tag: 'Right'; value: A }

These changes would allow handy roundtrips when using JSON.stringify

import * as assert from 'assert'
import { right } from 'fp-ts/lib/Either'

const testRoundtrip = <A>(codec: t.Type<A>) => {
  const OptionFromJSON = createOptionFromJSON(codec)
  return (ma: Option<A>) => {
    const result = OptionFromJSON.decode(JSON.parse(JSON.stringify(ma)))
    assert.deepStrictEqual(result, right(ma))
  }
}

const test = testRoundtrip(t.number)

test(none)
test(some(1))
gcanti commented 5 years ago

https://github.com/gcanti/io-ts-types/pull/86