axios-wrapper.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. /* eslint-disable require-atomic-updates */
  2. /* eslint-disable no-console */
  3. /* eslint-disable no-param-reassign */
  4. import _ from 'lodash';
  5. import Axios from 'axios';
  6. import { Util, Error } from 'naf-core';
  7. import { Loading } from 'element-ui';
  8. import UserUtil from './user-util';
  9. const { trimData, isNullOrUndefined } = Util;
  10. const { ErrorCode } = Error;
  11. let currentRequests = 0;
  12. export default class AxiosWrapper {
  13. constructor({ baseUrl = '', unwrap = true } = {}) {
  14. this.baseUrl = baseUrl;
  15. this.unwrap = unwrap;
  16. }
  17. // 替换uri中的参数变量
  18. static merge(uri, query = {}) {
  19. if (!uri.includes(':')) {
  20. return uri;
  21. }
  22. const keys = [];
  23. const regexp = /\/:([a-z0-9_]+)/gi;
  24. let res;
  25. // eslint-disable-next-line no-cond-assign
  26. while ((res = regexp.exec(uri)) != null) {
  27. keys.push(res[1]);
  28. }
  29. keys.forEach(key => {
  30. if (!isNullOrUndefined(query[key])) {
  31. uri = uri.replace(`:${key}`, query[key]);
  32. }
  33. });
  34. return uri;
  35. }
  36. $get(uri, query, options) {
  37. return this.$request(uri, null, query, options);
  38. }
  39. $delete(uri, query, options = {}) {
  40. return this.$request(uri, null, query, { ...options, method: 'delete' });
  41. }
  42. $post(uri, data = {}, query, options) {
  43. return this.$request(uri, data, query, options);
  44. }
  45. async $request(uri, data, query, options) {
  46. // 过滤key:''的情况
  47. query = _.pickBy(query, val => val !== '');
  48. if (!uri) console.error('uri不能为空');
  49. if (_.isObject(query) && _.isObject(options)) {
  50. const params = query.params ? query.params : query;
  51. options = { ...options, params };
  52. } else if (_.isObject(query) && !query.params) {
  53. options = { params: query };
  54. } else if (_.isObject(query) && query.params) {
  55. options = query;
  56. }
  57. if (!options) options = {};
  58. if (options.params) options.params = trimData(options.params);
  59. const url = AxiosWrapper.merge(uri, options.params);
  60. currentRequests += 1;
  61. // const loadingInstance = Loading.service({ spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.5)' });
  62. try {
  63. const axios = Axios.create({
  64. baseURL: this.baseUrl,
  65. });
  66. const user = localStorage.getItem('user');
  67. if (user) {
  68. axios.defaults.headers.common.Authorization = encodeURI(user);
  69. }
  70. axios.defaults.headers.common.dtype = 'pc';
  71. let res = await axios.request({
  72. method: isNullOrUndefined(data) ? 'get' : 'post',
  73. url,
  74. data,
  75. responseType: 'json',
  76. ...options,
  77. });
  78. res = res.data || {};
  79. const { errcode, errmsg, details } = res;
  80. if (errcode) {
  81. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  82. if (errcode === -7) {
  83. window.location.replace('https://zhjy.jilinjobs.cn:8080/dist/school.html#/navi');
  84. // console.log(uri);
  85. return;
  86. }
  87. return res;
  88. }
  89. // unwrap data
  90. if (this.unwrap) {
  91. // res = _.omit(res, ['errcode', 'errmsg', 'details']);
  92. const keys = Object.keys(res);
  93. if (keys.length === 1 && keys.includes('data')) {
  94. res = res.data;
  95. }
  96. }
  97. return res;
  98. } catch (err) {
  99. let errmsg = '接口请求失败,请稍后重试';
  100. if (err.response) {
  101. const { status, data = {} } = err.response;
  102. if (status === 401) errmsg = '用户认证失败,请重新登录';
  103. if (status === 403) errmsg = '当前用户不允许执行该操作';
  104. if (status === 400 && data.errcode) {
  105. const { errcode, errmsg, details } = data;
  106. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
  107. return data;
  108. }
  109. if (data && data.error) {
  110. const { status, error, message } = data;
  111. console.warn(`[${uri}] fail: ${status}: ${error}-${message}`);
  112. return { errcode: status || ErrorCode.SERVICE_FAULT, errmsg: error, details: message };
  113. }
  114. }
  115. console.error(`[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} - ${err.message}`);
  116. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
  117. } finally {
  118. currentRequests -= 1;
  119. if (currentRequests <= 0) {
  120. currentRequests = 0;
  121. // loadingInstance.close();
  122. }
  123. }
  124. }
  125. }