@@ -2,25 +2,45 @@ import { handlers } from "@/app/auth"
22import { NextResponse } from 'next/server'
33import { NextRequest } from 'next/server'
44import { getProxyConfig } from "@/proxy-config"
5+ import { HttpsProxyAgent } from "https-proxy-agent"
56
67const TIMEOUT_DURATION = 60000 ;
78
9+ // 扩展 RequestInit 类型以包含 Node.js 特定选项
10+ interface ExtendedRequestInit extends RequestInit {
11+ agent ?: HttpsProxyAgent ;
12+ timeout ?: number ;
13+ }
14+
815// 定义超时 Promise 的类型
916type TimeoutPromise = Promise < never >
1017
1118export async function GET ( request : NextRequest ) : Promise < Response > {
1219 try {
13- const { isEnabled } = getProxyConfig ( ) ;
20+ const { isEnabled, httpsAgent } = getProxyConfig ( ) ;
1421
15- if ( isEnabled ) {
16- // 使用超时机制
17- const timeoutPromise : TimeoutPromise = new Promise ( ( _ , reject ) =>
18- setTimeout ( ( ) => reject ( new Error ( 'Request timeout' ) ) , TIMEOUT_DURATION )
19- ) ;
20- const response = await Promise . race ( [ handlers . GET ( request ) , timeoutPromise ] ) ;
21- return response instanceof Response ? response : NextResponse . json ( response ) ;
22+ // 只在认证请求时使用代理
23+ if ( isEnabled && request . url . includes ( '/api/auth' ) ) {
24+ console . log ( 'originalFetch!!!!!!!!!!:' , global . fetch ) ;
25+ const originalFetch = global . fetch ;
26+ global . fetch = async ( input : RequestInfo | URL , init ?: RequestInit ) => {
27+ const extendedInit : ExtendedRequestInit = {
28+ ...init ,
29+ agent : httpsAgent ,
30+ timeout : TIMEOUT_DURATION ,
31+ } ;
32+ return originalFetch ( input , extendedInit ) ;
33+ } ;
34+
35+ try {
36+ const response = await handlers . GET ( request ) ;
37+ return response instanceof Response ? response : NextResponse . json ( response ) ;
38+ } finally {
39+ // 请求完成后恢复原始的 fetch
40+ global . fetch = originalFetch ;
41+ }
2242 } else {
23- // 不使用超时机制
43+ // 非认证请求使用普通 fetch
2444 const response = await handlers . GET ( request ) ;
2545 return response instanceof Response ? response : NextResponse . json ( response ) ;
2646 }
0 commit comments