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

[zod-openapi] unable to infer response type from c.status() #723

Open
fumieval opened this issue Aug 30, 2024 · 1 comment
Open

[zod-openapi] unable to infer response type from c.status() #723

fumieval opened this issue Aug 30, 2024 · 1 comment

Comments

@fumieval
Copy link
Contributor

When the response schemas are heterogeneous depending on the status code, the typechecker erroneously forces the response type to one of them.

Here's a reproducing example:

/*
JSONRespondReturn<{ id string; }, 200 | 404>' is not assignable to type 'TypedResponse<{ message string; }, 404, "json">
*/
import { describe, it } from 'vitest'
import { OpenAPIHono, createRoute, z } from '../src/index'

describe('createRoute', () => {
  const config = {
    method: 'get',
    path: '/',
    request: {},
    responses: {
      200: {
        content: {
          'application/json': {
            schema: z.object({
              id: z.string(),
            }),
          },
        },
        description: 'Retrieve a value',
      },
      404: {
        content: {
          'application/json': {
            schema: z.object({
              message: z.string(),
            }),
          },
        },
        description: 'Not found',
      },
    },
  } as const
  const route = createRoute(config)

  const app = new OpenAPIHono()
  app.openapi(route, async (c) => {
    if (Math.random() > 0.5) {
      c.status(404)
      return c.json({ message: 'Not found' })
    } else {
      c.status(200)
      return c.json({ id: '42' })
    }
  })

  it('should compile', () => {})
})

The workaround is to specifying the status code via the second argument.

  // this works
  app.openapi(route, async (c) => {
    if (Math.random() > 0.5) {
      return c.json({ message: 'Not found' }, 404)
    } else {
      return c.json({ id: '42' }, 200)
    }
  })

If it's a known limitation, perhaps it's worth documenting it somewhere in https://hono.dev/examples/zod-openapi

@yusukebe
Copy link
Member

Hi @fumieval

It's not a bug. You should specify the status number explicitly. It's the same as RPC mode:

https://hono.dev/docs/guides/rpc#status-code

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

No branches or pull requests

2 participants