asteasolutions / zod-to-openapi

A library that generates OpenAPI (Swagger) docs from Zod schemas
MIT License
916 stars 57 forks source link

Using `refine()` and `transform` together for an object #238

Closed yusukebe closed 3 months ago

yusukebe commented 3 months ago

Hi, thank you for such a great library!

This is like a question but may be a bug report. Can we use refine() and transform() together for an object? The following code will throw TypeScript type errors:

import { OpenAPIRegistry, extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi'
import { z } from '@hono/zod-openapi'

extendZodWithOpenApi(z)

const user = z
  .object({ name: z.string(), age: z.string() })
  .refine((val) => val.name || val.age, {
    message: 'name or age required',
    path: ['name', 'age']
  })
  .transform((data) => data) // <--- Add .transform()

const registry = new OpenAPIRegistry()

registry.registerPath({
  method: 'get',
  path: '/users/{id}',
  summary: 'Get a single user',
  request: {
    params: user, // <-- error
    query: user, // <-- error
    body: {
      content: {
        'application/json': {
          schema: user
        }
      }
    }
  },
  responses: {}
})

This is related to the https://github.com/honojs/middleware/issues/560

AGalabov commented 3 months ago

@yusukebe - yes this is something that we could try and fix. If you want to open a PR - feel free to do so. If not - I will try and take a look at it in the near future.

AGalabov commented 3 months ago

@yusukebe it turned out that it was a very easy fix. This is now released as part of our v7.1.0 Release

yusukebe commented 3 months ago

@AGalabov Wow quick. Thank you very much!