astahmer / openapi-zod-client

Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)
openapi-zod-client.vercel.app
788 stars 84 forks source link

feat: allow x-zod-schema extension property in openapi docs to override generated schema #237

Open h-sigma opened 1 year ago

h-sigma commented 1 year ago

What it does

Allows the user to override the zod schema generated for an openapi schema via an extension property:

NullableDateTime:
      description: Date and time in ISO 8601 format, or null.
      type: [string, "null"]
      format: date-time
      x-zod-schema: z.coerce.date().nullable()

This should generate:

const NullableDateTime = z.coerce.date().nullable();

Enable It Via

The new CLI option: --x-zod-schema.

Reasoning

Tweaking the generated client via only handlebars is... quite limiting. In cases where there is a conflict between the spec author/developer and the openapi-zod-client plugin in terms of what should be generated, or when the generator turns out to be inflexible, this extension can provide a much cheaper alternative to forking the project.

Take my example above: I wanted coercion on my date types because js Date class is what I like to use in my form components. That's not possible out of the box with the plugin. In fact, I dropped my attempt at modifying the library to add an option for coercions halfway through and wrote this instead.

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
openapi-zod-client ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 30, 2023 6:34am
astahmer commented 1 year ago

hey, adding an escape hatch seems like a good idea, can you add a test and a changeset ?

h-sigma commented 1 year ago

definitely. but it'll have to be after today's work day or tomorrow. @astahmer I notice there is code to emit types, e.g. in the template

export const {{@key}}{{#if (lookup ../emittedType @key)}}: z.ZodType<{{@key}}>{{/if}} = {{{this}}};

apparently to aid with circular type dependencies. Will the code in openApiToTypescript.ts be needed to be changed in order to accommodate this feature?

astahmer commented 1 year ago

Will the code in openApiToTypescript.ts be needed to be changed in order to accommodate this feature?

hm I don't think so since you only want to override the zod schemas ? or maybe you'd also like to make a x-ts-schema in case the zod schema differs too much from the generated TS type ?

astahmer commented 11 months ago

I'm not sure, is it ready to be merged ?

ecamellini commented 8 months ago

Hi all, are there updates on this PR? I have the same need on some projects I'm working on 😇

astahmer commented 8 months ago

feel free to take over the PR and update it so it can be merged