| 16 | } |
| 17 | |
| 18 | export class APIProxy { |
| 19 | private logger: any |
| 20 | private basePathPrefix: string |
| 21 | |
| 22 | constructor(options: ProxyOptions) { |
| 23 | this.logger = serverLogger.withTag(options.loggerTag) |
| 24 | this.basePathPrefix = options.basePathPrefix |
| 25 | } |
| 26 | |
| 27 | async handleRequest(request: NextRequest, { params }: ProxyRouteParams) { |
| 28 | try { |
| 29 | const { path } = await params |
| 30 | const pathString = path.join("/") |
| 31 | |
| 32 | const url = `${this.basePathPrefix}/${pathString}` |
| 33 | |
| 34 | const searchParams = request.nextUrl.searchParams |
| 35 | const queryString = searchParams.toString() |
| 36 | const fullUrl = queryString ? `${url}?${queryString}` : url |
| 37 | |
| 38 | const options: any = { |
| 39 | method: request.method, |
| 40 | headers: { |
| 41 | "Authorization": `Bearer ${await getServerToken()}`, |
| 42 | "Content-Type": "application/json", |
| 43 | }, |
| 44 | } |
| 45 | |
| 46 | if (request.method !== "GET" && request.method !== "HEAD") { |
| 47 | const body = await request.text() |
| 48 | if (body) { |
| 49 | options.body = body |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | this.logger.info("Forwarding API request", { |
| 54 | method: request.method, |
| 55 | url: fullUrl, |
| 56 | }) |
| 57 | |
| 58 | // 转发请求到远程API |
| 59 | const response = await serverRemoteFetch(fullUrl, options) |
| 60 | |
| 61 | return NextResponse.json(response) |
| 62 | } catch (error) { |
| 63 | this.logger.error("Error forwarding API request", { error }) |
| 64 | return NextResponse.json( |
| 65 | { error: "Internal server error", message: String(error) }, |
| 66 | { status: 500 }, |
| 67 | ) |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | export function createProxyHandlers(options: ProxyOptions) { |
| 73 | const proxy = new APIProxy(options) |
nothing calls this directly
no outgoing calls
no test coverage detected