@traversable/derive-codec
TypeScript icon, indicating that this package has built-in type declarations

0.0.9ย โ€ขย Publicย โ€ขย Published

แฏ“๐˜๐—ฟ๐—ฎ๐˜ƒ๐—ฒ๐—ฟ๐˜€๐—ฎ๐—ฏ๐—น๐—ฒ/๐—ฑ๐—ฒ๐—ฟ๐—ถ๐˜ƒ๐—ฒ-๐—ฐ๐—ผ๐—ฑ๐—ฒ๐—ฐ


Re-use your schema to derive a bi-directional codec (with compiled codecs coming soon!)


NPM Version ย  TypeScript ย  Static Badge ย  npm ย 
npm bundle size (scoped) ย  Static Badge ย  Static Badge ย 
TypeScript Playground ย ย โ€ขย ย  npm


Overview

  • Instructions: to install the .codec method on all schemas, all you need to do is import @traversable/derive-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)

Example

Play with this example in the TypeScript playground.

import { t } from '@traversable/schema'
import '@traversable/derive-codec'
//      ^^ this installs the `.pipe` 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 }

Readme

Keywords

none

Package Sidebar

Install

npm i @traversable/derive-codec

Weekly Downloads

23

Version

0.0.9

License

none

Unpacked Size

56.1 kB

Total Files

58

Last publish

Collaborators

  • ahrjarrett