Skip to content

Support for z.lazy() and recursive schemas #140

Description

@rattrayalex

Currently, this code (copied from zod's recursive types docs):

const baseCategorySchema = z.object({
  name: z.string(),
});

type Category = z.infer<typeof baseCategorySchema> & {
  subcategories: Category[];
};

const categorySchema: z.ZodType<Category> = baseCategorySchema.extend({
  subcategories: z.lazy(() => categorySchema.array()),
});

const registry = new OpenAPIRegistry();
registry.register("Category", categorySchema);

const generator = new OpenAPIGenerator(registry.definitions, "3.0.0");

try {
  const document = generator.generateDocument({
    info: {
      version: "1.0.0",
      title: "My API",
    },
    servers: [{ url: "v1" }],
  });
  console.log(document);
} catch (err) {
  console.error(err);
}

Throws this error:

UnknownZodTypeError {
  message: 'Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.',
  data: {
    currentSchema: { getter: [Function (anonymous)], typeName: 'ZodLazy' },
    schemaName: undefined
  }
}

Ideally, it would generate an OpenAPI spec like this:

const document = {
  components: {
    schemas: {
      Category: {
        type: "object",
        properties: {
          name: { type: "string" },
          subcategories: {
            type: "array",
            items: { $ref: "#/components/schemas/Category" },
          },
        },
      },
    },
  },
  ...etc,
};

This may require automatic resolution of registered schemas to $refs, which I filed here: #142

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions