功能

umi-request的工具类封装

源码参考

  1. /**
  2. * 实现一个简单的Map cache, 稍后可以挪到 utils中, 提供session local map三种前端cache方式.
  3. * 1. 可直接存储对象 2. 内存无5M限制 3.缺点是刷新就没了, 看反馈后期完善.
  4. */
  5. import { parse, stringify } from 'qs';
  6. /**
  7. * lamia
  8. * Map类型的缓存配置
  9. */
  10. export class MapCache {
  11. constructor(options) {
  12. // lamia 声明对象cache
  13. this.cache = new Map();
  14. // lamia 声明对象timer
  15. this.timer = {};
  16. // lamia 初始化最大缓存配置
  17. this.extendOptions(options);
  18. }
  19. // lamia this.maxCache定义maxCache
  20. extendOptions(options) {
  21. this.maxCache = options.maxCache || 0;
  22. }
  23. // lamia 获取值
  24. get(key) {
  25. return this.cache.get(JSON.stringify(key));
  26. }
  27. // lamia 设置值
  28. set(key, value, ttl = 60000) {
  29. // 如果超过最大缓存数, 删除头部的第一个缓存.
  30. if (this.maxCache > 0 && this.cache.size >= this.maxCache) {
  31. // lamia this.cache.keys(): 获取所有的cache的keys, 获取第一个值
  32. const deleteKey = [...this.cache.keys()][0];
  33. // lamia 删除对象第一个this.cache的值
  34. this.cache.delete(deleteKey);
  35. // lamia 如果deleteKey,第一个对应的值所对应的timer已经存在,则清除对应的定时器
  36. if (this.timer[deleteKey]) {
  37. clearTimeout(this.timer[deleteKey]);
  38. }
  39. }
  40. // lamia 获取cacheKey
  41. const cacheKey = JSON.stringify(key);
  42. // lamia 设置cacheKey对应的值: value
  43. this.cache.set(cacheKey, value);
  44. // lamia 如果需要设置过期时间,建立对应的定时器,当ttl时间到时,清除对应的cache, 并且清除定时器
  45. if (ttl > 0) {
  46. this.timer[cacheKey] = setTimeout(() => {
  47. this.cache.delete(cacheKey);
  48. delete this.timer[cacheKey];
  49. }, ttl);
  50. }
  51. }
  52. // lamia 删除key对应的cache, 及对应的timer
  53. delete(key) {
  54. const cacheKey = JSON.stringify(key);
  55. delete this.timer[cacheKey];
  56. return this.cache.delete(cacheKey);
  57. }
  58. // lamia 清除定时器,清除cache;
  59. clear() {
  60. this.timer = {};
  61. return this.cache.clear();
  62. }
  63. }
  64. /**
  65. * 请求异常
  66. */
  67. export class RequestError extends Error {
  68. constructor(text, request, type = 'RequestError') {
  69. super(text);
  70. this.name = 'RequestError';
  71. this.request = request;
  72. this.type = type;
  73. }
  74. }
  75. /**
  76. * 响应异常
  77. *
  78. */
  79. export class ResponseError extends Error {
  80. constructor(response, text, data, request, type = 'ResponseError') {
  81. super(text || response.statusText);
  82. // 定义错误的名称
  83. this.name = 'ResponseError';
  84. // 定义数据
  85. this.data = data;
  86. // 最终的响应
  87. this.response = response;
  88. // 请求
  89. this.request = request;
  90. // 设置响应错误的类型
  91. this.type = type;
  92. }
  93. }
  94. /**
  95. * http://gitlab.alipay-inc.com/KBSJ/gxt/blob/release_gxt_S8928905_20180531/src/util/request.js#L63
  96. * 支持gbk
  97. * 将对应的文件类型,转化成对应的GBK的格式
  98. */
  99. export function readerGBK(file) {
  100. return new Promise((resolve, reject) => {
  101. // 读取对应的file文件流
  102. const reader = new FileReader();
  103. // reader加载时获取对应的结果流
  104. reader.onload = () => {
  105. resolve(reader.result);
  106. };
  107. // 当读取失败是,返回对应的reject
  108. reader.onerror = reject;
  109. // 设置对应的文件格式GBK
  110. reader.readAsText(file, 'GBK'); // setup GBK decoding
  111. });
  112. }
  113. /**
  114. * 安全的JSON.parse
  115. */
  116. export function safeJsonParse(data, throwErrIfParseFail = false, response = null, request = null) {
  117. // 通过try的方式,如果json.parse格式化数据错误,则执行对应的catch
  118. try {
  119. return JSON.parse(data);
  120. } catch (e) {
  121. // 当throwErrIfParseFail为true时, 则曝出异常
  122. if (throwErrIfParseFail) {
  123. throw new ResponseError(response, 'JSON.parse fail', data, request, 'ParseError');
  124. }
  125. } // eslint-disable-line no-empty
  126. // 正常输出对应的data
  127. return data;
  128. }
  129. // 等待一定时间执行超时的返回
  130. export function timeout2Throw(msec, request) {
  131. return new Promise((_, reject) => {
  132. setTimeout(() => {
  133. reject(new RequestError(`timeout of ${msec}ms exceeded`, request, 'Timeout'));
  134. }, msec);
  135. });
  136. }
  137. // If request options contain 'cancelToken', reject request when token has been canceled
  138. // 取消promise的操作
  139. export function cancel2Throw(opt) {
  140. return new Promise((_, reject) => {
  141. if (opt.cancelToken) {
  142. opt.cancelToken.promise.then(cancel => {
  143. reject(cancel);
  144. });
  145. }
  146. });
  147. }
  148. const toString = Object.prototype.toString;
  149. // Check env is browser or node
  150. // 验证环境变量
  151. export function getEnv() {
  152. let env;
  153. // Only Node.JS has a process variable that is of [[Class]] process
  154. if (typeof process !== 'undefined' && toString.call(process) === '[object process]') {
  155. // For node use HTTP adapter
  156. env = 'NODE';
  157. }
  158. if (typeof XMLHttpRequest !== 'undefined') {
  159. env = 'BROWSER';
  160. }
  161. return env;
  162. }
  163. // 判断是否为数组类型
  164. export function isArray(val) {
  165. return typeof val === 'object' && Object.prototype.toString.call(val) === '[object Array]';
  166. }
  167. // 判断是否为Url的查询参数 URLSearchParams
  168. export function isURLSearchParams(val) {
  169. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  170. }
  171. // 判断是否为日期格式类型
  172. export function isDate(val) {
  173. return typeof val === 'object' && Object.prototype.toString.call(val) === '[object Date]';
  174. }
  175. // 判断是否为isObject
  176. export function isObject(val) {
  177. return val !== null && typeof val === 'object';
  178. }
  179. // 遍历数组或者对象,通过callback的方式调用
  180. export function forEach2ObjArr(target, callback) {
  181. if (!target) return;
  182. if (typeof target !== 'object') {
  183. target = [target];
  184. }
  185. if (isArray(target)) {
  186. for (let i = 0; i < target.length; i++) {
  187. callback.call(null, target[i], i, target);
  188. }
  189. } else {
  190. for (let key in target) {
  191. if (Object.prototype.hasOwnProperty.call(target, key)) {
  192. callback.call(null, target[key], key, target);
  193. }
  194. }
  195. }
  196. }
  197. export function getParamObject(val) {
  198. if (isURLSearchParams(val)) {
  199. return parse(val.toString(), { strictNullHandling: true });
  200. }
  201. if (typeof val === 'string') {
  202. return [val];
  203. }
  204. return val;
  205. }
  206. // 将请求转化成query请求的字符串格式
  207. export function reqStringify(val) {
  208. return stringify(val, { arrayFormat: 'repeat', strictNullHandling: true });
  209. }
  210. /**
  211. * lamia
  212. * 合并请求配置
  213. * @param {*} options
  214. * @param {*} options2Merge
  215. */
  216. export function mergeRequestOptions(options, options2Merge) {
  217. return {
  218. ...options,
  219. ...options2Merge,
  220. headers: {
  221. ...options.headers,
  222. ...options2Merge.headers,
  223. },
  224. params: {
  225. ...getParamObject(options.params),
  226. ...getParamObject(options2Merge.params),
  227. },
  228. method: (options2Merge.method || options.method || 'get').toLowerCase(),
  229. };
  230. }