56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { PUBLIC_TO_UPSTREAM } from "@/lib/api-paths";
|
|
|
|
const API_BASE_URL = process.env.API_BASE_URL ?? "http://api-server:3000";
|
|
|
|
async function forward(
|
|
request: NextRequest,
|
|
path: string[],
|
|
): Promise<NextResponse> {
|
|
const hash = path[0];
|
|
const route = PUBLIC_TO_UPSTREAM[hash];
|
|
if (!route) {
|
|
return NextResponse.json({ error: "Not Found" }, { status: 404 });
|
|
}
|
|
const target = `${API_BASE_URL}/${route.upstream}${route.trailingSlash ? "/" : ""}`;
|
|
|
|
const init: RequestInit = {
|
|
method: request.method,
|
|
headers: {
|
|
"content-type":
|
|
request.headers.get("content-type") ?? "application/json",
|
|
},
|
|
};
|
|
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
init.body = await request.text();
|
|
}
|
|
|
|
try {
|
|
const upstream = await fetch(target, init);
|
|
const body = await upstream.text();
|
|
return new NextResponse(body, {
|
|
status: upstream.status,
|
|
headers: {
|
|
"content-type":
|
|
upstream.headers.get("content-type") ?? "application/json",
|
|
},
|
|
});
|
|
} catch (err) {
|
|
return NextResponse.json({ error: String(err) }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function GET(
|
|
request: NextRequest,
|
|
ctx: { params: Promise<{ path: string[] }> },
|
|
): Promise<NextResponse> {
|
|
return forward(request, (await ctx.params).path);
|
|
}
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
ctx: { params: Promise<{ path: string[] }> },
|
|
): Promise<NextResponse> {
|
|
return forward(request, (await ctx.params).path);
|
|
}
|