cloudflare / chanfana

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

How to Use Itty Router OpenAPI with Next.js? #105

Closed c1DeepInside closed 8 months ago

c1DeepInside commented 8 months ago

Next with itty-router-openapi

I'm currently exploring the possibility of integrating itty router openapi into a Next.js project. My main concern revolves around the fact that Next.js comes with its own built-in routing system. I'm curious about how these two can coexist or if it's even feasible to implement itty router openapi within the Next.js environment.

c1DeepInside commented 8 months ago

Example to use itty-router-openapi with next

Here how to use Next with itty router

To integrate itty router openapi with Next.js, you can create a custom API route that captures all requests. For instance, you might have a route like app/api/gpt/[slug].ts.

import {
  OpenAPIRoute,
  OpenAPIRouter,
  Str,
} from '@cloudflare/itty-router-openapi'
import { json } from 'itty-router-extras'

const router = OpenAPIRouter({
  schema: {
    info: {
      title: 'GPT Companion',
      version: '1.0',
    },
    servers: [
      {
        url: 'http://localhost:3000',
        description: 'Development server',
      },
    ],
  },
  openapi_url: '/api/gpt/openapi.json',
})

class GiveWord extends OpenAPIRoute {
  static schema = {
    requestBody: {
      word: new Str({ required: true }),
    },
    responses: {
      '200': {
        description: 'word comeback)',
        schema: {
          word: new Str(),
        },
      },
    },
  }

  async handle(
    request: Request,
    data: {
      body: {
        word: string
      }
    },
  ) {
    return json({ word: data.body.word })
  }
}

router.post('/api/gpt/word', GiveWord)

router.all('*', () => new Response('404 Not Found...', { status: 200 }))

In Next.js 14, to intercept GET and POST requests and pass them to itty router, you need to set up your API routes to forward these requests to therouter. This can be done by returning router.handle(req) within your API route handlers.

export async function POST(req: Request) {
  return router.handle(req)
}

export async function GET(req: Request) {
  return router.handle(req)
}