Skip to content

proposal: enhanced zod Integration for fetch Client #2598

@soartec-lab

Description

@soartec-lab

Overview

This proposal aims to simplify Zod schema generation, eliminate duplication with TypeScript type definitions, and enable runtime validation through seamless integration with the fetch client.

Proposed Features

  1. Unified Schema Generation Control: Manage TypeScript type definitions and Zod schemas uniformly through the schemas option
  2. Runtime Validation for Fetch Responses: Automatically validate responses with Zod schemas
  3. Replace TypeScript Type Definitions with Zod Schemas: Infer fetch client response types from Zod schemas

1. Unified Schema Generation Control

export default defineConfig({
  petstore: {
    input: { target: './petstore.yaml' },
    output: {
      mode: 'tags-split',
      client: 'swr',
      target: 'src/gen/endpoints',
-     schemas: 'src/gen/models',
+     schemas: {
+       path: 'src/gen/models',
+       type: ['typescript', 'zod'],  // Generate both
+     },
      mock: true,
    },
  },
- petstoreZod: {
-   input: { target: './petstore.yaml' },
-   output: {
-     mode: 'tags-split',
-     client: 'zod',
-     target: 'src/gen/endpoints',
-     fileExtension: '.zod.ts',
-   },
- },
});

Benefits: Simplifies configuration files and enables unified control of all schema generation through the schemas option


2. Runtime Validation for Fetch Responses

Configuration example:

export default {
  output: {
    override: {
      zod: {
        runtimeValidation: true
      }
    }
  }
}

Generated code example:

export const getPet = async (petId: number): Promise<Pet> => {
  const res = await fetch(`/pets/${petId}`);
  const data = await res.json();
  return PetSchema.parse(data);  // Automatic validation
};

Benefits:

  • Improved type safety through runtime validation
  • Protection against legacy systems or untrusted APIs
  • Early detection of API specification violations

3. Replace TypeScript Type Definitions with Zod Schemas

Configuration example:

export default {
  output: {
    override: {
      fetch: {
        useZodSchemaResponse: true
      }
    }
  }
}

Benefits: Reduces duplication by inferring fetch client response types from Zod schemas instead of TypeScript type definitions


Overall Benefits

  • Gradual adoption: Each feature is independent and can be enabled as needed
  • Improved developer experience: Simple configuration for quick start
  • Runtime safety: Enhanced type safety through runtime validation
  • Legacy system support: Provides a defensive layer against untrusted APIs

Metadata

Metadata

Assignees

Labels

fetchFetch client related issuezodZod related issue

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions