File size: 1,973 Bytes
4b81334
6be14c8
4b81334
5e00fb2
 
4b81334
 
5e00fb2
4b81334
 
6be14c8
5e00fb2
 
8ac2dd1
5e00fb2
4b81334
8ac2dd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e00fb2
 
 
 
 
 
4b81334
 
 
 
 
5e00fb2
 
 
 
 
4b81334
5e00fb2
4b81334
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { type NextRequest, NextResponse } from "next/server";
import { backendUrl } from "@/lib/backend-url";

// Stream multipart uploads to FastAPI. Calling request.formData() here buffers
// the whole PDF in Next.js and can fail before the backend sees the file.

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

export async function POST(request: NextRequest) {
  const backend = backendUrl();
  const headers = new Headers();
  const requestContentType = request.headers.get("content-type");
  const requestContentLength = request.headers.get("content-length");
  const cookie = request.headers.get("cookie");

  console.info("[upload proxy] received upload request", {
    contentType: requestContentType,
    contentLength: requestContentLength,
    hasBody: Boolean(request.body),
  });

  if (!requestContentType?.includes("multipart/form-data")) {
    return NextResponse.json(
      {
        detail: `Upload request must be multipart/form-data; received ${requestContentType ?? "no content-type"}.`,
      },
      { status: 400 }
    );
  }

  if (requestContentType) headers.set("content-type", requestContentType);
  if (cookie) headers.set("cookie", cookie);

  if (!request.body) {
    return NextResponse.json({ detail: "Upload request did not include a file body." }, { status: 400 });
  }

  let response: Response;
  try {
    response = await fetch(`${backend}/upload`, {
      method: "POST",
      body: request.body,
      duplex: "half",
      headers,
    } as RequestInit & { duplex: "half" });
  } catch (error) {
    return NextResponse.json(
      { detail: `Could not reach the backend upload service: ${(error as Error).message}` },
      { status: 502 }
    );
  }

  const contentType = response.headers.get("content-type") ?? "text/plain; charset=utf-8";
  const body = await response.text();

  return new NextResponse(body, {
    status: response.status,
    headers: { "content-type": contentType },
  });
}