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

Generate TS enum and z.nativeEnum openapi zod client #224

Open palaniichukdmytro opened 1 year ago

palaniichukdmytro commented 1 year ago

I think it's common issue for generate type from open api spec. I am using with zodios https://github.com/astahmer/openapi-zod-client/ openapi-zod-client. But did not found any possible solution to generate enum , instead I see that only union types is possible . Any idea to generate TS enum to use this enum in a code durin compile time .

Example schema json

 {
            "name": "format",
            "in": "query",
            "required": false,
            "schema": {
              "enum": [
                "flat",
                "grouped"
              ],
              "type": "string",
              "default": "flat",
              "title": "Format"
            }

By default it's generate a union with type flag enabled or via handlebars templates you can do yourself. But it is not possible to generate TS enum or z.nativeEnums

Output:

export const Format= z.enum([
  'Flat',
  'Grouped',
])
export type FormatType = z.infer<typeof Format> // union one

Exacted/Desire output


export enum FormatType {
  Flat = 'Flat', 
  Grouped = 'Grouped'
}

export const Format = z.nativeEnum(FormatType)
palaniichukdmytro commented 1 year ago

I am thinking it might be helpful to add flag like --export-enums and generate them. Is it refer to this line https://github.com/astahmer/openapi-zod-client/blob/df5dd72c227fe36a38954e26a8a2f57fb96766e6/lib/src/openApiToTypescript.ts#L170

smth like this

t.enum(${name}, [
...schema.enum
]);