axios-wrapper.js 5.0 KB

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