<br /> <h1 align="center">áŻđđżđŽđđ˛đżđđŽđŻđšđ˛/đđ°đľđ˛đşđŽ-đ°đźđąđ˛đ°</h1> <br />
npm install @traversable/schema-codec
Re-use your @traversable/schema to derive a bi-directional codec
- Instructions: to install the .codec method on all schemas, all you need to do is import @traversable/schema-codec.
- To create a covariant codec (similar to zod's .transform), use .codec.pipe
- To create a contravariant codec (similar to zod's .preprocess), use .codec.extend (WIP)
Play with this example in the TypeScript playground.
``typescript.pipe
import { t } from '@traversable/schema'
import '@traversable/schema-codec'
// ^^ this installs the and .extend methods on all schemas
let User = t
.object({ name: t.optional(t.string), createdAt: t.string }).codec // <-- notice we're pulling off the .codec property
.pipe((user) => ({ ...user, createdAt: new Date(user.createdAt) }))
.unpipe((user) => ({ ...user, createdAt: user.createdAt.toISOString() }))
let fromAPI = User.parse({ name: 'Bill Murray', createdAt: new Date().toISOString() })
// ^? let fromAPI: Error | { name?: string, createdAt: Date}
if (fromAPI instanceof Error) throw fromAPI
fromAPI
// ^? { name?: string, createdAt: Date }
let toAPI = User.encode(fromAPI)
// ^? let toAPI: { name?: string, createdAt: string }
``