(url: string, options: HttpRequestOptions = {})
| 426 | } |
| 427 | |
| 428 | static async makeRequest(url: string, options: HttpRequestOptions = {}): Promise<HttpResponse> { |
| 429 | return new Promise((resolve, reject) => { |
| 430 | try { |
| 431 | const parsedUrl = new URL(url); |
| 432 | if (!['http:', 'https:'].includes(parsedUrl.protocol)) { |
| 433 | reject(new Error('不支持的协议')); |
| 434 | return; |
| 435 | } |
| 436 | } catch { |
| 437 | reject(new Error('无效的URL')); |
| 438 | return; |
| 439 | } |
| 440 | |
| 441 | const { method = 'GET', headers = {}, data, timeout = 30000 } = options; |
| 442 | const isHttps = url.startsWith('https:'); |
| 443 | const client = isHttps ? https : http; |
| 444 | |
| 445 | const req = client.request(url, { |
| 446 | method, |
| 447 | headers: { |
| 448 | 'Content-Type': 'application/json', |
| 449 | 'User-Agent': 'TeleBox/1.0', |
| 450 | ...headers |
| 451 | }, |
| 452 | timeout |
| 453 | }, (res: any) => { |
| 454 | |
| 455 | res.setEncoding('utf8'); |
| 456 | let body = ''; |
| 457 | let dataLength = 0; |
| 458 | const maxResponseSize = 10 * 1024 * 1024; |
| 459 | |
| 460 | res.on('data', (chunk: string) => { |
| 461 | dataLength += chunk.length; |
| 462 | if (dataLength > maxResponseSize) { |
| 463 | req.destroy(); |
| 464 | reject(new Error('响应数据过大')); |
| 465 | return; |
| 466 | } |
| 467 | body += chunk; |
| 468 | }); |
| 469 | |
| 470 | res.on('end', () => { |
| 471 | try { |
| 472 | |
| 473 | const cleanBody = HttpClient.cleanResponseText(body); |
| 474 | const parsedData = cleanBody ? JSON.parse(cleanBody) : {}; |
| 475 | resolve({ |
| 476 | status: res.statusCode || 0, |
| 477 | data: parsedData, |
| 478 | headers: res.headers |
| 479 | }); |
| 480 | } catch (error) { |
| 481 | |
| 482 | resolve({ |
| 483 | status: res.statusCode || 0, |
| 484 | data: HttpClient.cleanResponseText(body), |
| 485 | headers: res.headers |
no test coverage detected