Skip to content

Add option to exclude input schema variants from OpenAPI components #214

@francisdaigle

Description

@francisdaigle

When registering Zod schemas with the global registry, fastify-type-provider-zod always generates both Schema and SchemaInput variants in OpenAPI components/schemas, even when they are completely identical:

{
  "Token": { "maxLength": 12, "minLength": 12, "type": "string" },
  "TokenInput": { "maxLength": 12, "minLength": 12, "type": "string" }
}

When generating TypeScript types from the OpenAPI spec (using openapi-typescript, orval, etc.), frontend developers typically only need the output schema:

type User = components["schemas"]["User"];

export const createMockUser = (): User => ({
  createdAt: new Date().toISOString(),
  email: 'john@example.com',
  id: 1,
  name: 'John Doe',
  updatedAt: new Date().toISOString(),
});

An optional configuration parameter could be added to createJsonSchemaTransformObject to exclude Input schema variants. This would be a non-breaking change:

export type CreateJsonSchemaTransformObjectOptions = {
  schemaRegistry?: $ZodRegistry<{ id?: string | undefined }>
  zodToJsonConfig?: ZodToJsonConfig
  excludeInputSchemas?: boolean  // NEW
}

export const createJsonSchemaTransformObject =
  ({
    schemaRegistry = globalRegistry,
    zodToJsonConfig = {},
    excludeInputSchemas = false,  // NEW
  }: CreateJsonSchemaTransformObjectOptions): SwaggerTransformObject =>
  (input) => {
    ...
    
    const inputSchemas = excludeInputSchemas 
      ? {}
      : zodRegistryToJson(schemaRegistry, 'input', zodToJsonConfig) // NEW
    
    const outputSchemas = zodRegistryToJson(schemaRegistry, 'output', zodToJsonConfig)
    
    ...
import {
    createJsonSchemaTransformObject,
    jsonSchemaTransform,
} from "fastify-type-provider-zod";

await fastify.register(swagger, {
    openapi: {
    info: {
        description: "Template API documentation",
        title: "Template API",
        version: "1.0.0",
    },
    servers: [],
    },
    transform: jsonSchemaTransform,
    transformObject: createJsonSchemaTransformObject({
        excludeInputSchemas: true,
    }),
});

Would you be open to a PR?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions