honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
424 stars 145 forks source link

Zod OpenAPI router combining with stream TS type mismatch issue #600

Closed owenizedd closed 2 months ago

owenizedd commented 3 months ago

Background:

Code:

export const readRouter = new OpenAPIHono({ router: new RegExpRouter() });

const streamJSONRoute = createRoute({
  method: "get",
  path: "/",
  tags: ["Read"],
  request: {},
  responses: {
    200: {
      content: {} as Promise<Response>,
      description: "Stream JSON",
    },
  },
});
readRouter.openapi(streamJSONRoute, async (c) => {
  return stream(c, async (stream) => {
    // Write a process to be executed when aborted.
    stream.onAbort(() => {
      console.log("Aborted!");
    });
    // Write a Uint8Array.
    await stream.write(new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]));
  });
});

Above code will result ts compiler compains on line: content: {} as Promise<Response>,:

Type 'Promise<Response>' is not assignable to type 'Partial<Record<ZodMediaType, ZodMediaTypeObject>>'.

If I make createRoute's responses to be responses: {} the router will compain:

Argument of type '(c: Context<Env, "/", {}>) => Promise<Response>' is not assignable to parameter of type 'Handler<Env, "/", {}, Promise<never>>'.
yusukebe commented 3 months ago

Hi @owenizedd

Try to remove content: {}:

const streamJSONRoute = createRoute({
  method: 'get',
  path: '/',
  tags: ['Read'],
  request: {},
  responses: {
    200: {
      description: 'Stream JSON'
    }
  }
})

In the current Zod OpenAPI, if the content property exists, it requires TypeResponse, not Response.

owenizedd commented 2 months ago

Thanks I forgot to mention it does work :)