HonoH
Hono10mo ago
M

createRoute Wrapper typing

This may not be entirely on topic, but perhaps someone has asked a similar question.
How to preserve typing?
I'm not that good at TypeScript, I understand that I need to use generics, I looked at the source code, but I still can't fully understand how to do this.

Example:
import { z, createRoute, OpenAPIHono } from '@hono/zod-openapi';

const server = new OpenAPIHono({});
type Method = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace';

function customCreateRoute(
  method: Method,
  path: string,
  request: any,
  response: any
) {
  return createRoute({
    method: method,
    path: path,
    requestBody: {
      content: {
        'application/json': {
          schema: request,
        },
      },
    },
    responses: {
      200: {
        content: {
          'application/json': {
            schema: response,
          },
        },
        description: '',
      },
    },
  });
}

const route = customCreateRoute(
  'get',
  '/user/{id}',
  z.object({}),
  z.object({ name: z.string() })
);

server.openapi(route, async (context) => {
  const id = context.req.param('id');
  return context.json({});
});
Was this page helpful?