cloudflare/chanfana

Chanfana using Hono and Swagger UI

marceloverdijk opened this issue · 1 comments

Looking at the Chanfana Minimal Hono Example

import { fromHono, OpenAPIRoute } from 'chanfana'
import { Hono } from 'hono'
import { z } from 'zod'

export class GetPageNumber extends OpenAPIRoute {
  schema = {
    request: {
      params: z.object({
        id: z.string().min(2).max(10),
      }),
      query: z.object({
        page: z.number().int().min(0).max(20),
      }),
    },
  }

  async handle(c) {
    const data = await this.getValidatedData<typeof this.schema>()

    return c.json({
      id: data.params.id,
      page: data.query.page,
    })
  }
}

// Start a Hono app
const app = new Hono()

// Setup OpenAPI registry
const openapi = fromHono(app)

// Register OpenAPI endpoints
openapi.get('/entry/:id', GetPageNumber)

// Export the Hono app
export default app

It uses the "normal" hono and zod imports, and not the OpenAPIHono from https://hono.dev/examples/zod-openapi which I assume is the recommended way with Canfana?

To expose the SwaggerUI we can do:

app.get('/ui', swaggerUI({ url: '/doc' }));

but how to expose the openapi spec under /doc using Chanfana and Hono?

Actually this was quite simple to do, but my approach above was wrong.

There was no need to install @hono/swagger-ui nor to do app.get('/ui', swaggerUI({ url: '/doc' }));.

Just use do this and it worked:

// Setup OpenAPI registry
const openapi = fromHono(app, {
    docs_url: "/",
});