(url, opts = {}, type)
| 585 | } |
| 586 | // 请求 |
| 587 | async function http(url, opts = {}, type) { |
| 588 | const start = Date.now() |
| 589 | let timeout = HTTP_TIMEOUT + 1 * 1000 |
| 590 | timeout = $.isSurge() ? timeout / 1000 : timeout |
| 591 | let reqOpts = { |
| 592 | url, |
| 593 | // headers: { |
| 594 | // 'Cache-Control': 'no-cache', |
| 595 | // Pragma: 'no-cache', |
| 596 | // }, |
| 597 | ...opts, |
| 598 | } |
| 599 | $.log(`🔗 链接`, reqOpts.url) |
| 600 | let isBinary = $.lodash_get(opts, 'binary-mode') |
| 601 | if (isBinary) { |
| 602 | $.log(`二进制模式`) |
| 603 | } |
| 604 | let res |
| 605 | let body |
| 606 | let bodyLength |
| 607 | // if (type === 'mock') { |
| 608 | // $.lodash_set(opts, 'binary-mode', true) |
| 609 | // } |
| 610 | try { |
| 611 | res = await Promise.race([ |
| 612 | $.http.get(reqOpts), |
| 613 | new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), HTTP_TIMEOUT)), |
| 614 | ]) |
| 615 | // $.log('ℹ️ res', res) |
| 616 | // $.log('ℹ️ res', $.toStr(res)) |
| 617 | // $.log('ℹ️ res', $.toStr(res)) |
| 618 | const status = $.lodash_get(res, 'status') || $.lodash_get(res, 'statusCode') || 200 |
| 619 | $.log('ℹ️ res status', status) |
| 620 | |
| 621 | const headers = $.lodash_get(res, 'headers') |
| 622 | // $.log('ℹ️ res headers', $.toStr(headers)) |
| 623 | const contentType = $.lodash_get(headers, 'content-type') || $.lodash_get(headers, 'Content-Type') |
| 624 | |
| 625 | if (isBinary) { |
| 626 | body = $.lodash_get(res, 'rawBody') || $.lodash_get(res, 'body') |
| 627 | } else { |
| 628 | body = $.lodash_get(res, 'body') || $.lodash_get(res, 'rawBody') |
| 629 | } |
| 630 | |
| 631 | // $.log('ℹ️ res body', body) |
| 632 | // $.log(body) |
| 633 | // $.log($.toStr(body)) |
| 634 | // console.log(body) |
| 635 | try { |
| 636 | $.log(`ℹ️ req body type`, typeof body) |
| 637 | // $.log(`ℹ️ req body constructor`, body.constructor) |
| 638 | } catch (e) {} |
| 639 | $.log(`⏱ 请求耗时:${Math.round(((Date.now() - start) / 1000) * 100) / 100} 秒\n └ ${reqOpts.url}`) |
| 640 | bodyLength = body?.length |
| 641 | $.log('ℹ️ res body length', bodyLength) |
| 642 | if (type === 'mock' && bodyLength > MAX_BODY_LENGTH) { |
| 643 | throw new Error('too large') |
| 644 | } |
no test coverage detected