Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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 z.lazy() and recursive schemas #140

Closed
rattrayalex opened this issue May 18, 2023 · 1 comment
Closed

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

rattrayalex opened this issue May 18, 2023 · 1 comment

Comments

@rattrayalex
Copy link

rattrayalex commented May 18, 2023

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

@AGalabov
Copy link
Collaborator

@rattrayalex thank you for this. Lazy schemas are something that we do not support at all as of today. I'll take a look at it.

@asteasolutions asteasolutions locked and limited conversation to collaborators Nov 16, 2023
@AGalabov AGalabov converted this issue into discussion #191 Nov 16, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants