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

Refactor to separate itty-router from openapi logic #151

Closed G4brym closed 3 weeks ago

G4brym commented 1 month ago

This refactors the OpenAPI logic and adds support for latest versions of itty-router and possibly other router (like hono)

The new version will require users to instantiate their own itty-router router like:

import { fromIttyRouter } from '@cloudflare/itty-router-openapi'
import { AutoRouter } from 'itty-router'
import { ToDoGet } from './todo'

const openapiRouter = fromIttyRouter(AutoRouter())
openapiRouter.get('/todo', ToDoGet)

export default openapiRouter

Breaking changes:

Additions:

Migration guide:

Minimal Hono example

import { extendZodWithOpenApi, fromHono, OpenAPIRoute } from '@cloudflare/itty-router-openapi'
import { Hono } from 'hono'
import { z } from 'zod'

extendZodWithOpenApi(z)

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,
    })
  }
}

const app = new Hono()
const openapi = fromHono(app)

openapi.get('/entry/:id', GetPageNumber)
export default app
github-actions[bot] commented 1 month ago

🧪 A prerelease is available for testing 🧪

You can install this latest build in your project with:

npm install --save https://prerelease-registry.devprod.cloudflare.dev/itty-router-openapi/runs/9555081565/npm-package-itty-router-openapi-151

Or you can immediately run this with npx:

npx https://prerelease-registry.devprod.cloudflare.dev/itty-router-openapi/runs/9555081565/npm-package-itty-router-openapi-151
carafelix commented 1 month ago

That's great! From a quick glance, it looks like the current openAPIRoute's would be compatible with this new version, that's good news on my book, since that could have been the main migration cost. Gotta say, the class based endpoints it's a beautiful abstraction. That's mostly why I prefer this package over hono-zod. It makes much more sense to encapsulate the handler with the schema, than the route with the schema. And I have not found any other router with this capabilities. I know this is not a very contributing comment, but nevertheless, sometimes, a few honest words are good to keep up the spirit, and therefore, keep the good work coming down the river. I can see this package becoming a standard for api development.

carafelix commented 3 weeks ago

Awesome! I'll check the new stuff