HttpService.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /** 默认头信息 */
  2. const DEFAULT_HEAD = {
  3. 'Content-Type': 'application/json',
  4. 'Accept-Charset': 'utf-8',
  5. /** 为解决跨域问题 */
  6. 'Origin': '*'
  7. };
  8. type HTTPRequestMethod = "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE";
  9. const HREQM: { [key in HTTPRequestMethod]: string } = {
  10. CONNECT: 'lightslategray',
  11. HEAD: 'cadetblue',
  12. OPTIONS: 'thistle',
  13. GET: 'lightgreen',
  14. PUT: 'darkcyan',
  15. DELETE: 'lightcoral',
  16. POST: 'deepskyblue',
  17. PATCH: 'silver',
  18. TRACE: 'steelblue',
  19. }
  20. /**
  21. * 创建请求头
  22. * @param conf
  23. */
  24. function createHeader(conf?: { [field: string]: string }) {
  25. let header = new Headers();
  26. [DEFAULT_HEAD, conf].forEach(list => {
  27. if (!list || list == null) return void 0;
  28. for (let field in list) header.append(field, Reflect.get(list, field));
  29. });
  30. return header;
  31. }
  32. /**
  33. * 格式化请求数据
  34. * @param param 请求数据
  35. * @param type 格式类型
  36. */
  37. function FormateData(param: { [name: string]: string | number }, type: 'json' | 'form' | 'search') {
  38. let data: string | FormData;
  39. if (type === 'json') data = JSON.stringify(param);
  40. else if (type === 'search') {
  41. let arr = [];
  42. for (let name in param) arr.push(`${name}=${param[name]}`);
  43. data = arr.join('&');
  44. } else if (type === 'form') {
  45. data = new FormData();
  46. for (let name in param) data.set(name, String(param[name]));
  47. }
  48. return data;
  49. }
  50. /**
  51. * 创建一个请求对象
  52. * @param url 请求路径
  53. * @param data 请求参数
  54. * @param method 请求方法类型
  55. * @param head 请求头配置
  56. */
  57. function createRequest(url: string, data: any, method?: HTTPRequestMethod, head?: { [name: string]: string }) {
  58. let body = FormateData(data, 'json');
  59. let options: RequestInit = {
  60. method: method ?? "GET",
  61. headers: createHeader(head)
  62. }
  63. if (options.method == 'POST') options.body = body;
  64. let request = new Request(url, options);
  65. return request;
  66. }
  67. /** 向服务器发送请求 */
  68. export async function http_send(...args: Parameters<typeof createRequest>) {
  69. args[2] = args[2] ?? 'GET';
  70. let req_token = mtec.string.randomToken(8, 36, t => !tokan_map.has(t));
  71. tokan_map.set(req_token, tokan_map.size);
  72. // mtec.log.tag([
  73. // ['SERVICE', 'slategray'],
  74. // [args[2], Reflect.get(HREQM, args[2])],
  75. // ['>>', 'dodgerblue']
  76. // ].map(_=>_.join(':')).join(';'), args[0].split('/').slice(3).join('/'), '\n--------------\nHEADERS:', args[3], '\nDATA:', args[1], '\n--------------\n');
  77. let start_date = new Date();
  78. let response: Response;
  79. let delay = 0;
  80. let data: any;
  81. let try_count = 0;
  82. while (!response?.ok && try_count < 3) {
  83. response = await fetch(createRequest(...args))
  84. .then(res => res)
  85. .catch(err => {
  86. // console.log('请求失败信息', JSON.stringify(err));
  87. log_response('单次请求失败', req_token, args[0], start_date, delay, try_count, data, -100, undefined);
  88. return void 0;
  89. });
  90. delay = Date.now() - start_date.valueOf();
  91. data = response?.ok ? await response.json() : undefined;
  92. try_count++;
  93. if (response && response.ok) {
  94. } else {
  95. __exception_call_list__.forEach(call => call(req_token, try_count, delay, response?.status ?? -101));
  96. }
  97. }
  98. if (try_count > 1) {
  99. log_response('触发接口重试', req_token, args[0], start_date, delay, try_count, data, response?.status ?? -102, response);
  100. __exception_call_list__.forEach(call => call(req_token, try_count, delay, response?.status ?? -102));
  101. } else if (delay > 5000) {
  102. log_response('请求延迟过高', req_token, args[0], start_date, delay, try_count, data, response?.status ?? -103, response);
  103. __exception_call_list__.forEach(call => call(req_token, try_count, delay, response?.status ?? -103));
  104. }
  105. if (!response?.ok) {
  106. log_response('异常接口最终信息', req_token, args[0], start_date, delay, try_count, data, response?.status ?? -104, response);
  107. __exception_call_list__.forEach(call => call(req_token, try_count, delay, response?.status ?? -104));
  108. }
  109. mtec.log.tag([
  110. ['SERVICE', 'slategray'],
  111. [args[2], Reflect.get(HREQM, args[2])],
  112. ['<<', 'seagreen'],
  113. data ? ['OK', 'springgreen'] : ['ERR', 'red'],
  114. [delay + ' ms', 'silver']
  115. ].map(_ => _.join(':')).join(';'), args[0].split('/').slice(3).join('/'), '\n--------------\nRESPONSE:', response, '\nDATA:', data, '\n--------------\n');
  116. tokan_map.delete(req_token);
  117. return data;
  118. }
  119. type __exception_call__ = (token: string, try_count: number, delay: number, status: number) => void;
  120. const __exception_call_list__: Array<__exception_call__> = [];
  121. const tokan_map: Map<string, number> = new Map();
  122. export function on_network_exception(call: __exception_call__) {
  123. __exception_call_list__.push(call);
  124. }
  125. function log_response(tag: string, token: string, url: string, start_date: Date, delay: number, try_count: number, data: any, status: number, response: Response) {
  126. // console.log(tag,
  127. // '\n请求接口: '+url,
  128. // '\n请求Token: '+token,
  129. // '\n请求时间: '+start_date.toLocaleString(),
  130. // '\n请求延迟: '+delay+' ms',
  131. // '\n请求次数: '+try_count,
  132. // '\n请求数据: '+JSON.stringify(data),
  133. // '\n请求状态: '+status,
  134. // '\n请求结果[Response]: '+JSON.stringify(response)
  135. // );
  136. }