commonbaseapp / zodex

The missing zod (de)?serialization library
MIT License
38 stars 5 forks source link
serialization zod

Zodex

Type-safe (de)serialization library for zod. It both serializes and simplifies types into a JSON format, in the following ways:

{ "type": "string", "defaultValue": "hi" }
{ "type": "number", "min": 23, "max": 42 }

Installation

pnpm add zodex
# or
yarn add zodex
# or
npm install zodex

Usage

import { z } from "zod";
import { zerialize } from "zodex";

const someZodType = z.discriminatedUnion("id", [
  z.object({ id: z.literal("a"), count: z.number().optional() }),
  z.object({ id: z.literal("b") }),
]);
const shape = zerialize(someZodType);

Now typeof shape will be

type Shape = {
  type: "discriminatedUnion";
  discriminator: "id";
  options: [
    {
      type: "object";
      properties: {
        id: { type: "literal"; value: "a" };
        count: { type: "number"; isOptional: true };
      };
    },
    { type: "object"; properties: { id: { type: "literal"; value: "b" } } }
  ];
};

which is exactly equal to its runtime value (shown in YAML for brevity, you probably shouldn't use YAML):

type: "discriminatedUnion"
discriminator: "id"
options:
  - type: "object"
    properties:
      id:
        type: "literal"
        value: "a"
      count:
        type: "number"
        isOptional: true
  - type: "object"
    properties:
      id:
        type: "literal"
        value: "b"

Options

Both zerialize and dezerialize accept an options object with the same properties.

Since Zod does not allow the specification of the names of effects (refinements, transforms, and preprocesses), we allow you to supply as options maps of names to effects so that these can be part of serialization and deserialization. Note that due to technical limitations, we cannot support the regular refine() method (and it will be ignored) but superRefine() is supported. If none of these options are supplied, the effects will be omitted.

Properties:

Roadmap

Caveats