Skip to content

feat: pass zod schema to custom fetch response implementation#3226

Open
Tarvion wants to merge 5 commits into
orval-labs:masterfrom
Tarvion:master
Open

feat: pass zod schema to custom fetch response implementation#3226
Tarvion wants to merge 5 commits into
orval-labs:masterfrom
Tarvion:master

Conversation

@Tarvion

@Tarvion Tarvion commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

Motivation

Currently, when using a custom mutator together with Zod runtime validation, there is no straightforward way to verify the returned data. This makes it harder to ensure that responses conform to the expected shape.

This PR proposes passing the corresponding Zod schema to the custom mutator when runtime validation is enabled, allowing proper validation of the response data.

Currently generated Code:

export const listPets = async (
  params?: ListPetsParams,
  options?: RequestInit,
): Promise<listPetsResponse> => {
  return customInstance<listPetsResponse>(getListPetsUrl(params), {
    ...options,
    method: 'GET',
  });
};

The same Code with the new change:

export const listPets = async (
  params?: ListPetsParams,
  options?: RequestInit,
): Promise<listPetsResponse> => {
  return customInstance<listPetsResponse>(getListPetsUrl(params), {
    ...options,
    method: 'GET',
    schema: Pets,
  });
};

Changes

  • Pass the corresponding Zod schema into the custom fetch response mutator if runtime validation is enabled

Summary by CodeRabbit

  • New Features

    • Optional flag to include request schema in fetch/mutator arguments for consumers needing schema-aware calls.
  • Refactor

    • Reworked how request/validation options are composed and forwarded to mutators, hooks, and custom fetch paths.
    • No public API shape changes or breaking behavior introduced.

@coderabbitai

coderabbitai Bot commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Refactors how request options are constructed: introduces rawFetchFnOptions (URL getter + merged global options + method/headers/body), computes schemaValueRef earlier when enabled, derives validateFetchFnOptions (appending schema if applicable), and passes validateFetchFnOptions to mutator/custom-fetch and hook call sites.

Changes

Cohort / File(s) Summary
Fetch options & call sites
packages/fetch/src/index.ts
Add rawFetchFnOptions; compute schemaValueRef before deriving options; derive validateFetchFnOptions (conditionally include schema when includeZodSchemaInArguments enabled and schema ≠ void); update mutator and hook/custom-fetch call sites to pass validateFetchFnOptions.
Type flag addition
packages/core/src/types.ts
Add optional includeZodSchemaInArguments?: boolean to NormalizedOverrideOutput and OverrideOutput interfaces to opt into including Zod schema in runtime call arguments.

Sequence Diagram(s)

sequenceDiagram
    participant Gen as Code Generator
    participant Caller as Generated Call Site
    participant Mut as Mutator/CustomFetch
    participant Val as Optional Validator

    rect rgba(200,200,255,0.5)
    Gen->>Caller: create rawFetchFnOptions (url getter, merged global opts, method, headers, body)
    Gen->>Caller: compute schemaValueRef (if includeZodSchemaInArguments && schema not void)
    Gen->>Caller: derive validateFetchFnOptions (append schema if present)
    end

    Caller->>Mut: call(mutator/customFetch, validateFetchFnOptions)
    alt Mutator performs validation
        Mut->>Val: validate(response, schema)
        Val-->>Mut: validation result
    end
    Mut-->>Caller: return response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • melloware

Poem

🐇 I hopped through lines to stitch a seam,

Collected opts and chased a dream.
A schema tucked beneath the page,
Passed along to calm the rage.
Little hop — a safer stage!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately describes the main change: adding Zod schema passing to custom fetch implementations. It is specific, concise, and directly reflects the primary feature being implemented.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/fetch/src/index.ts (1)

432-432: Be aware: Zod validation throws ZodError on failure.

The .parse() method on line 432 will throw a ZodError if validation fails. The current implementation doesn't wrap this in a try-catch, so validation errors will propagate up as thrown errors rather than being handled like fetch errors. This might be the intended behavior, but ensure downstream code handles ZodError appropriately.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/fetch/src/index.ts` at line 432, The assignment using
${schemaValueRef}.parse(parsedBody) can throw a ZodError; update the code in the
fetch response handling to either use ${schemaValueRef}.safeParse(parsedBody)
and handle the returned success/error path (convert validation errors into the
same error shape used for fetch failures), or wrap the .parse call in a
try/catch that catches ZodError and transforms/logs it into a controlled error
before rethrowing/returning; locate the usage of ${schemaValueRef} and the data
assignment to implement one of these approaches so validation failures are
handled consistently with other fetch errors.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/fetch/src/index.ts`:
- Around line 396-399: The template string validateFetchFnOptions incorrectly
always appends "schema: ${schemaValueRef}" regardless of isValidateResponse,
causing syntax errors and passing schema when validation is disabled; fix by
building validateFetchFnOptions conditionally—use rawFetchFnOptions alone when
isValidateResponse is false, and only append ", schema: ${schemaValueRef}" (or
include the schema property) when isValidateResponse is true, or alternatively
choose between fetchFnOptions and validateFetchFnOptions at call sites (the
places using validateFetchFnOptions) so that schemaValueRef is only present when
isValidateResponse is true.

---

Nitpick comments:
In `@packages/fetch/src/index.ts`:
- Line 432: The assignment using ${schemaValueRef}.parse(parsedBody) can throw a
ZodError; update the code in the fetch response handling to either use
${schemaValueRef}.safeParse(parsedBody) and handle the returned success/error
path (convert validation errors into the same error shape used for fetch
failures), or wrap the .parse call in a try/catch that catches ZodError and
transforms/logs it into a controlled error before rethrowing/returning; locate
the usage of ${schemaValueRef} and the data assignment to implement one of these
approaches so validation failures are handled consistently with other fetch
errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0d7578c5-75b8-46b6-ae98-2c98f86228d3

📥 Commits

Reviewing files that changed from the base of the PR and between fdde32b and a680976.

📒 Files selected for processing (1)
  • packages/fetch/src/index.ts

Comment thread packages/fetch/src/index.ts Outdated
@melloware

Copy link
Copy Markdown
Collaborator

looks like build is failing

@melloware melloware added the zod Zod schema client related issue label Apr 13, 2026
@melloware melloware added the fetch Fetch client related issue label Apr 14, 2026
@melloware melloware requested a review from soartec-lab April 14, 2026 12:02

@soartec-lab soartec-lab left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Tarvion

Let's make this the following option: override.mutator.includeZodSchemaInArgments: boolean
This argument will only be added if this flag is true and schema.type is zod.

@luizfeldmann

Copy link
Copy Markdown

This would be a great improvement

@Tarvion

Tarvion commented Apr 22, 2026

Copy link
Copy Markdown
Contributor Author

@Tarvion

Let's make this the following option: override.mutator.includeZodSchemaInArgments: boolean This argument will only be added if this flag is true and schema.type is zod.

That sounds like a good idea. Will do that

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/fetch/src/index.ts`:
- Around line 427-432: The code unconditionally injects schema:
${schemaValueRef} into validateFetchFnOptions and always uses
validateFetchFnOptions at mutator call sites (validateFetchFnOptions symbol),
which breaks users unless they opt in and only works for zod-backed schemas;
update the logic to only include the schema when isValidateResponse &&
override?.mutator?.includeZodSchemaInArgments === true && isZodOutput is true
(use the existing isZodOutput, isValidateResponse,
override.mutator.includeZodSchemaInArgments and schemaValueRef symbols), create
a new mutatorFetchFnOptions string that falls back to fetchFnOptions when the
opt-in/schema conditions are not met, and replace uses of validateFetchFnOptions
at the mutator call sites with mutatorFetchFnOptions so no schema/key is emitted
unless the opt-in and zod-output checks pass.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 976b8d52-169d-4a34-830e-eee8cb18f9c0

📥 Commits

Reviewing files that changed from the base of the PR and between 225ef96 and 2abea9c.

📒 Files selected for processing (1)
  • packages/fetch/src/index.ts

Comment thread packages/fetch/src/index.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/types.ts`:
- Line 171: The public interface OverrideOutput is missing the
includeZodSchemaInArguments?: boolean flag that was added to
NormalizedOverrideOutput; add includeZodSchemaInArguments?: boolean to the
OverrideOutput definition so callers can provide it in configs, and ensure the
config normalization code (the normalization routine that builds a
NormalizedOverrideOutput in utils/options.ts) continues to accept and spread
this property from OverrideOutput into NormalizedOverrideOutput (verify the same
property name is used where overrides are merged).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a855fe8d-4bd1-4bfb-bf75-d302a1bd2640

📥 Commits

Reviewing files that changed from the base of the PR and between 2abea9c and bb6c803.

📒 Files selected for processing (2)
  • packages/core/src/types.ts
  • packages/fetch/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/fetch/src/index.ts

Comment thread packages/core/src/types.ts
@soartec-lab

Copy link
Copy Markdown
Member

@Tarvion

This argument will only be added if this flag is true and schema.type is zod.

please check, and you should update normalize process

@melloware

Copy link
Copy Markdown
Collaborator

Looks like Snapshots are failing?

@hugo093 hugo093 mentioned this pull request May 5, 2026
27 tasks

@soartec-lab soartec-lab left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a fantastic feature. I've left a few comments, so please check those out. I look forward to your response.

* @default false
*/
useNullForOptional?: boolean;
includeZodSchemaInArguments?: boolean;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please normalize and specify the initial value for the boolean.

https://github.com/orval-labs/orval/blob/master/packages/orval/src/utils/options.ts

Suggested change
includeZodSchemaInArguments?: boolean;
includeZodSchemaInArguments: boolean;

: `body: JSON.stringify(${requestBodyParams})`
: '';
const fetchFnOptions = `${getUrlFnName}(${getUrlFnProperties}),
const rawFetchFnOptions = `${getUrlFnName}(${getUrlFnProperties}),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't think it was necessary to relinquish the variable name and rearrange the values ​​here.

schemaValueRef !== 'void' &&
typeof context.output.schemas === 'object' &&
context.output.schemas.type === 'zod';
const validateFetchFnOptions = `${rawFetchFnOptions}${includeZodSchema ? ',' : ''}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's best to include this process within the function that creates the fetch options.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fetch Fetch client related issue zod Zod schema client related issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants