Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for .refine to use if in generated json schema #76

Closed
akshay5995 opened this issue Jun 15, 2023 · 2 comments
Closed

Support for .refine to use if in generated json schema #76

akshay5995 opened this issue Jun 15, 2023 · 2 comments

Comments

@akshay5995
Copy link

akshay5995 commented Jun 15, 2023

Hey, first of thanks for this amazing package 🙏🏽

I'd love to have support for .refine to generate corresponding if condition in the json schema

Example schema

const someSchema = z
  .object({
    enable: z.boolean().default(false),
    id: z.string().optional(),
  })
  .refine((data) => {
    if (data.enable && !data.id) {
      return false;
    }

    return true;
  }, "id should be specified");

generated

{
  "type": "object",
  "properties": {
    "enable": {
      "type": "boolean",
      "default": false
    },
    "id": {
      "type": "string"
    }
  },
  "additionalProperties": false,
  "$schema": "http://json-schema.org/draft-07/schema#"
}

expected

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "enable": {
      "type": "boolean",
      "default": false
    },
    "id": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "enable": {
        "const": true
      }
    }
  },
  "then": {
    "required": ["id"]
  },
  "else": {
    "properties": {
      "id": {
        "type": "string"
      }
    }
  }
}

Let me know if there's a workaround for it too. Thanks!

@akshay5995 akshay5995 changed the title Support for .refine should use if and Support for .refine should use if and Jun 15, 2023
@akshay5995 akshay5995 changed the title Support for .refine should use if and Support for .refine to use if in generated json schema Jun 15, 2023
@StefanTerdell
Copy link
Owner

Thanks!

I don't think this is possible. The function defined in a refine could do anything, including side-effects. Your example is simple enough to be converted to a schema, yes - but that also means it could be expressed as a schema rather than in a refine. In this case, this would be the equivalent:

const someSchema = z.union([
  z
    .object({
      enable: z.literal(false).default(false),
      id: z.string(),
    })
    .partial(),
  z.object({
    enable: z.literal(true),
    id: z.string(),
  }),
]);

This would also give you type support, where as refine does not.

@akshay5995
Copy link
Author

Thanks! Understood will close the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants