turbo-eth / template-web3-app

⚡️ Web3 App Template built using Next.js, RainbowKit, SIWE, Disco, and more!
https://www.turboeth.xyz
MIT License
321 stars 89 forks source link

Refactor: Move api endpoints to app router #93

Closed marthendalnunes closed 1 year ago

marthendalnunes commented 1 year ago

This PR transitions the API endpoints from the pages router to the new app router, marking TurboETH's complete migration to the app router and eliminating the pages folder. This move also standardizes the implementation of API endpoints for integrations.

Now, every API endpoint associated with an integration should be located inside the integrations folder. For instance, if the openai integration requires an ask endpoint, the corresponding code should be housed in integrations/openai/api/ask.ts. The endpoint functions must maintain the Next convention for route handlers, employing named exports based on the HTTP method (GET, POST, PATCH, etc.):

import { OpenAIStream } from '@/integrations/openai/openai-stream'
import { ModelConfig } from '@/integrations/openai/types'

export async function POST(req: Request) {
  const { prompt, apiKey } = (await req.json()) as {
    prompt?: string
    apiKey?: string
  }
  if (!prompt) {
    return new Response('No prompt in the request', { status: 400 })
  }

  const payload: ModelConfig = {
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: prompt }],
    temperature: 0.7,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
    max_tokens: 600,
    stream: true,
    n: 1,
  }

  const stream = await OpenAIStream(payload, apiKey)
  return new Response(stream)
}

To expose the endpoint, the route handler file must reside at app/api/(integration-name)/(endpoint-name)/route/ts. For instance, the openai endpoint should be at app/api/openai/ask/route.ts:

export { POST } from '@/integrations/openai/api/ask'

export const runtime = 'edge'

This pattern applies to all migrated API endpoints and should be adhered to for any new additions.

The major obstacle in this migration was the lack of support for app router API endpoints from iron-session. The workaround employed the getIronSession method with an empty Response object to retrieve the session object, instead of using the unsupported withIronSessionApiRoute wrapper. Upon the launch of iron-session V8, which promises first-class support for the app router, the endpoints utilizing it will be updated accordingly.

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
light-turbo-eth ✅ Ready (Inspect) Visit Preview Jun 12, 2023 6:27pm
turbo-eth ✅ Ready (Inspect) Visit Preview Jun 12, 2023 6:27pm