cloudflare / chanfana

OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!
https://chanfana.pages.dev
MIT License
263 stars 35 forks source link

Chanfana using Hono and Swagger UI #160

Closed marceloverdijk closed 2 weeks ago

marceloverdijk commented 2 weeks ago

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?

marceloverdijk commented 2 weeks ago

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: "/",
});