import { NextRequest, NextResponse } from "next/server"; import { backendFetch } from "@/lib/backend"; import { cookies } from "next/headers"; const CACHE_REVALIDATE = 60 * 60 * 24; const CACHEABLE_RESOURCES = /^\/api\/(dictionary|collocations|examples)\//; function isCacheableResource(method: string, pathname: string, search: string) { return method === "GET" && !search && CACHEABLE_RESOURCES.test(pathname); } async function handler(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { const { path } = await params; const pathname = `/api/${path.join("/")}`; const hasBody = !["GET", "HEAD"].includes(request.method); const hasSession = (await cookies()).get("session")?.value !== undefined; const resource = isCacheableResource(request.method, pathname, request.nextUrl.search) && !hasSession; const response = await backendFetch(`${pathname}${request.nextUrl.search}`, { method: request.method, headers: hasBody ? { "Content-Type": request.headers.get("content-type") ?? "application/json" } : undefined, body: hasBody ? await request.text() : undefined, next: resource ? { revalidate: CACHE_REVALIDATE } : undefined, }); const headers = new Headers(); const contentType = response.headers.get("content-type"); if (contentType) headers.set("Content-Type", contentType); if (resource && response.ok) headers.set("Cache-Control", `public, s-maxage=${CACHE_REVALIDATE}`); return new NextResponse(await response.text(), { status: response.status, headers, }); } export { handler as GET, handler as POST, handler as PATCH, handler as DELETE };