zutils/dist/utils/net.util.cjs.map
2024-01-17 15:16:12 +08:00

1 line
6.5 KiB
Plaintext

{"version":3,"sources":["../../src/utils/net.util.ts","../../src/common/ZError.ts"],"sourcesContent":["import { ZError } from 'common/ZError'\n\nconst TIMEOUT_ERROR = new Error('timeout')\n\nconst hexRe = /^[0-9A-Fa-f]+$/gu\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options)\n if (!response.ok) {\n throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`)\n }\n return response\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await successfulFetch(request, options)\n const object = await response.json()\n return object\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string\n options?: RequestInit\n timeout?: number\n errorCodesToCatch?: number[]\n}) {\n let result\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n } else {\n result = await handleFetch(url, options)\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch)\n }\n return result\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(url: string, options?: RequestInit, timeout = 500): Promise<Response> {\n return Promise.race([\n successfulFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: any, codesToCatch: number[] = []) {\n if (!error) {\n return\n }\n\n const includesErrorCodeToCatch = codesToCatch.some(code =>\n error.message.includes(`Fetch failed with status '${code}'`),\n )\n\n if (\n error instanceof Error &&\n (includesErrorCodeToCatch || error.message.includes('Failed to fetch') || error === TIMEOUT_ERROR)\n ) {\n console.error(error)\n } else {\n throw error\n }\n}\n\nexport function generateHeader() {\n let random = function (start, end) {\n return (Math.random() * (end - start) + start) | 0\n }\n let getIp = function () {\n return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`\n }\n let time = Date.now()\n let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${\n (70 + Math.random() * 10) | 0\n }.0.4324.${(Math.random() * 100) | 0} Safari/537.36`\n const ip = getIp()\n return {\n 'Refresh-Token': (time -= 5000),\n 'Cache-Control': 'no-cache',\n 'User-Agent': useragent,\n 'X-Forwarded-For': ip,\n 'X-Real-IP': ip,\n 'Content-Type': 'application/json',\n }\n}\n\nexport const checkParamsNeeded = (...args) => {\n args.forEach(arg => {\n if (!arg) {\n throw new ZError(10, 'params mismatch')\n }\n })\n}\n","\nexport class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,SAAN,MAA8B;AAAA,EAMnC,YAAY,YAAoB,SAAiB;A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