honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
408 stars 141 forks source link

[zod-openapi] Support ZodLazy #643

Open Shyrogan opened 2 months ago

Shyrogan commented 2 months ago

Similarly to how zod-openapi does it: https://github.com/samchungy/zod-openapi/tree/master?tab=readme-ov-file#supported-zod-schema

Currently, we get the following error:

Unknown zod object type, please specify type and other OpenAPI props using ZodSchema.openapi.

A good example of usage would be the JSON schema from Zod's documentation:

const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
type Literal = z.infer<typeof literalSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const jsonSchema: z.ZodType<Json> = z.lazy(() =>
  z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
);
shakibhasan09 commented 1 month ago

Any update so far? I'm facing the same issue

coderhammer commented 1 month ago

Facing the same issue, did you find a workaround to support recursive types?

Shyrogan commented 1 month ago

Facing the same issue, did you find a workaround to support recursive types?

Sadly there is no other way than lazy

coderhammer commented 1 month ago

I ended up overwriting type with the .openapi method like this:

BaseSearchOrdersFiltersSchema.extend({
    oneOf: z
      .lazy(() => SearchOrdersFiltersSchema.array().optional())
      .openapi({
        type: "array",
        items: {
          type: "object",
        },
      }),

I'm sure there is a better way to define the openapi schema but this at least does not break the spec generation