File size: 1,210 Bytes
5960fdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { NextRequest } from 'next/server'

export const runtime = 'nodejs'

function backendBase(): string {
  return process.env.ASTRO_BACKEND_BASE_URL ?? 'http://127.0.0.1:8000'
}

async function proxy(req: NextRequest, params: { path: string[] }) {
  const path = `/${params.path.join('/')}`
  const url = new URL(req.url)
  const target = `${backendBase()}${path}${url.search}`

  const init: RequestInit = {
    method: req.method,
    headers: {
      'content-type': req.headers.get('content-type') ?? '',
    },
    cache: 'no-store',
  }

  if (req.method !== 'GET' && req.method !== 'HEAD') {
    init.body = await req.text()
  }

  const res = await fetch(target, init)
  const body = await res.arrayBuffer()
  return new Response(body, {
    status: res.status,
    headers: {
      'content-type': res.headers.get('content-type') ?? 'application/json; charset=utf-8',
    },
  })
}

export async function GET(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
  const params = await ctx.params
  return proxy(req, params)
}

export async function POST(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
  const params = await ctx.params
  return proxy(req, params)
}