Skip to content
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

Fix Handling of Optional Zod Fields with NestJS Swagger #194

Merged
merged 1 commit into from
Mar 29, 2024

Conversation

BEARlogin
Copy link

Dear Anatine Team,

I've encountered an issue where optional object fields defined with Zod are incorrectly treated as required by NestJS Swagger. Upon investigation, I discovered that NestJS Swagger defaults to marking fields as required unless explicitly stated otherwise. This behavior leads to a discrepancy when integrating Zod schemas, as fields intended to be optional are handled as required.

Issue Example:

Consider the following schema, where both pagination and filter are intended as optional fields:

const schema = z.object({
  pagination: z
    .object({
      limit: z.number(),
      offset: z.number(),
    })
    .optional(),
  filter: z
    .object({
      category: z.string().uuid(),
      userId: z.string().uuid(),
    })
    .optional(),
  sort: z.object({
    field: z.string(),
    order: z.string(),
  }),
});

In this scenario, NestJS Swagger incorrectly applies required: true to all fields, ignoring the optional designation provided by Zod.

Proposed Solution:

To address this issue, we must explicitly set required: false for fields where schemaObject.required is undefined. This ensures that our intent of marking fields as optional is accurately reflected in the generated Swagger documentation.

I believe this adjustment will enhance the integration compatibility between Zod and NestJS Swagger, ensuring that optional fields are correctly recognized and treated as such.

I look forward to your feedback on this proposed fix.

@BEARlogin BEARlogin changed the title make required field false if undefined Fix Handling of Optional Zod Fields with NestJS Swagger Mar 25, 2024
Copy link

nx-cloud bot commented Mar 25, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit ab4c5c6. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


✅ Successfully ran 2 targets

Sent with 💌 from NxCloud.

@Brian-McBride Brian-McBride merged commit 9cad0ec into anatine:main Mar 29, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants