Coder Social home page Coder Social logo

zod-compare's Introduction

⚖️ Zod Compare

Build npm

Compare two Zod schemas recursively.

zod-compare provides functions to compare Zod schemas, allowing you to determine whether two schemas are the same or compatible.

Installation

# npm
npm install zod zod-compare

# yarn
yarn add zod zod-compare

# pnpm
pnpm add zod zod-compare

Usage

import { z } from "zod";
import { isSameType, isCompatibleType } from "zod-compare";

isSameType(z.string(), z.string()); // true
isSameType(z.string(), z.number()); // false
isSameType(
  z.object({ name: z.string(), other: z.number() }),
  z.object({ name: z.string() }),
);
// false

isCompatibleType(
  z.object({ name: z.string(), other: z.number() }),
  z.object({ name: z.string() }),
);
// true

Advanced Usage

Custom Rules

You can use createCompareFn to create a custom comparison function.

import {
  createCompareFn,
  isSameTypePresetRules,
  defineCompareRule,
} from "zod-compare";

const customRule = defineCompareRule(
  "compare description",
  (a, b, next, recheck, context) => {
    // If the schemas are not having the same description, return false
    if (a.description !== b.description) {
      return false;
    }
    return next();
  },
);

const strictIsSameType = createCompareFn([
  customRule,
  ...isSameTypePresetRules,
]);

Debugging

You can pass a context object to the comparison functions to get more information about the comparison process.

const context = {
  stacks: [],
};
isSameType(
  z.object({ name: z.string(), other: z.number() }),
  z.object({ name: z.string(), other: z.string() }),
  context,
);

// type stacks = { name: string; target: [a: ZodType, b: ZodType]; }[]
console.log(context.stacks);

Caveats

The default rules isSameTypePresetRules will disregard any custom validations like min, max, length, among others. Additionally, these default rules cannot be utilized for comparing ZodLazy, ZodEffects, ZodDefault, ZodCatch, ZodPipeline, ZodTransformer, ZodError types.

If there is a necessity to compare these types, custom rules can be established using defineCompareRule.

API

isSameType

Compares two Zod schemas and returns true if they are the same.

import { isSameType } from "zod-compare";

type isSameType: (a: ZodType, b: ZodType, context?: CompareContext) => boolean;

createCompareFn

Creates a custom comparison function.

import { createCompareFn, defineCompareRule } from "zod-compare";

type defineCompareRule = (
  name: string,
  rule: CompareFn,
) => {
  name: string;
  rule: CompareFn;
};

type createCompareFn = (rules: CompareRule[]) => typeof isSameType;

// Example
const isSameType = createCompareFn(isSameTypePresetRules);
const isCompatibleType = createCompareFn(isCompatibleTypePresetRules);

isCompatibleType (Experimental API)

Compares two Zod schemas and returns true if they are compatible.

import { isCompatibleType } from "zod-compare";
// The `higherType` should be a looser type
// The `lowerType` should be a stricter type
type isCompatibleType: (higherType: ZodType, lowerType: ZodType) => boolean;

Preset Rules

You can use the preset rules isSameTypePresetRules and isCompatibleTypePresetRules to create custom comparison functions.

import { isSameTypePresetRules, isCompatibleTypePresetRules } from "zod-compare";

type isSameTypePresetRules: CompareRule[];
type isCompatibleTypePresetRules: CompareRule[];

// Example
const yourIsSameType = createCompareFn([customRule, ...isSameTypePresetRules]);

Types

type CompareContext = {
  stacks?: {
    name: string;
    target: [a: ZodType, b: ZodType];
  }[];
} & Record<string, unknown>;

type CompareFn = (
  a: ZodType,
  b: ZodType,
  next: () => boolean,
  recheck: (a: ZodType, b: ZodType) => boolean,
  context: CompareContext,
) => boolean;

type CompareRule = {
  name: string;
  compare: CompareFn;
};

License

MIT

zod-compare's People

Contributors

lawvs avatar github-actions[bot] avatar dependabot[bot] avatar

Stargazers

Juer.G Whang avatar Jonathan Pritchard avatar Zhazha_JiaYiZhen avatar YiJie avatar

Watchers

 avatar

zod-compare's Issues

[Proposal] Replace misc options with middleware

Motivation

The option of isSameType is messy.

export interface IsSameTypeOptions {
  ignoreValidations: true;
  ignoreOptional: boolean;
  ignoreNullable: boolean;
  ignoreReadOnly: false;
  // Some options are ambiguous
  ignoreBranded: boolean;
  // ...
}
  if (opts.ignoreBranded) {
    if (a instanceof z.ZodBranded) {
      a = a.unwrap();
    }
    if (b instanceof z.ZodBranded) {
      b = b.unwrap();
    }
    return isSameType(a, b, opts);
  } else {
    if (a instanceof z.ZodBranded || b instanceof z.ZodBranded) {
      // We can not distinguish different branded type
      // throw new Error("Can not distinguish different branded type!");
      return false;
    }
  }

Proposal

Replacing the ignore* options with middleware.

// Example middleware

const brandedMiddleware = (config) =>
  defineMiddleware(
    (
      context: Record<string, unknown> & {
        a: ZodType,
        b: ZodType,
        options: Options,
      },
      next
    ) => {
      if (
        config.uniqueBranded &&
        (a instanceof z.ZodBranded || b instanceof z.ZodBranded)
      ) {
        return false;
      }
      if (a instanceof z.ZodBranded) {
        context.a = a.unwrap();
      }
      if (b instanceof z.ZodBranded) {
        context.b = b.unwrap();
      }
      return next();
    }
  );

const debugMiddleware = defineMiddleware((a, b, context) => {
  const result = next();
  if (!result) {
    console.log(a, "!=", b);
  }
  return result;
});

isSameType(a, b, {
  middleware: [debugMiddleware, brandedMiddleware()],
  disableDefaultMiddleware: false,
});

Inspired by https://hono.dev/guides/middleware https://floating-ui.com/docs/middleware

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.