index.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import Request from './request'
  2. import apiList from './api'
  3. // import store from '../../store/index.js'
  4. import Tools from '../tools.js'
  5. const TAG_NAME="REQUEST INDEX.JS";
  6. let cacheSessions = {}; //会话存储
  7. //data._isRefresh用于第二次强制请求
  8. export default function api(url, data = {},isNeedLoading=false) {
  9. const request = new Request();
  10. let api = getApiObj(url);
  11. // console.log('api---',api,url);
  12. let cacheType = api.cacheType;
  13. const cacheKey = getCacheKey('',url,data)
  14. /**
  15. * 正常:return加工后config,用于真正request
  16. * 异常:调用cancel后,request不在向下进行。type:2 resolve缓存结束。1reject
  17. */
  18. request.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
  19. const token = uni.getStorageSync('token') || '';
  20. // console.log('request.interceptor.request',config);
  21. let res;
  22. //_isRefresh用于第二次请求
  23. if( cacheType === 'local' && !data._isRefresh){
  24. res = uni.getStorageSync(cacheKey);
  25. }else if( cacheType === 'session' && !data._isRefresh){
  26. // console.log('request.interceptor cacheType',cacheType,cacheSessions[cacheKey])
  27. // 第一次session--要判断否则JSON.parse报错
  28. if(cacheSessions[cacheKey]) res = JSON.parse(cacheSessions[cacheKey]);
  29. }
  30. if(res){
  31. //调用者继续向下运行 cancel,本方法继续向下进行
  32. cancel('已获得请求值,不再请求',res,2)
  33. // console.log('已获得请求值,不再请求---',cacheType,cacheSessions,res);
  34. return;
  35. }else if (api.auth && !token) {
  36. //request 调用者直接报错不再向下进行。本方法继续向下进行
  37. cancel('暂未登录,已阻止此次API请求~')
  38. setTimeout(()=>{
  39. uni.redirectTo({
  40. url:'/pages/index/loginMobile'
  41. })
  42. },800)
  43. return;
  44. }
  45. //正常情况下,返config用于下步请求~
  46. // console.log("request index",config);
  47. if (token) {
  48. config.data={...config.data,token};
  49. }
  50. return config;
  51. });
  52. request.interceptor.response((response) => { /* 请求之后拦截器 */
  53. //200情况
  54. const data = response.data;
  55. if( cacheType === 'local'){
  56. (data && data.code === 1) && uni.setStorage({key: cacheKey,data: data})
  57. }else if(cacheType === 'session'){
  58. // console.log('request.interceptor response before--',cacheKey,cacheSessions[cacheKey],JSON.stringify(data.data || ''));
  59. (data && data.code === 1) && (cacheSessions[cacheKey] = JSON.stringify(data || '')); //统一request.js message还要用提示
  60. // console.log('request.interceptor response after----',cacheSessions[cacheKey])
  61. }
  62. return response;
  63. }, (error) => { // 除200都在 ---request.js由validateStatus决定
  64. console.log('error--',error)
  65. if (error.statusCode) {
  66. if(error.statusCode === 401){
  67. const pages = getCurrentPages()
  68. if(pages.length > 1 && pages[pages.length - 1].route== 'pages/login/login'){
  69. //解决同时多个请求,都跳登录页情况
  70. reject(TAG_NAME,'已在登录页,无需在次进入')
  71. return;
  72. }
  73. // console.log(TAG_NAME,options.url,'重新登录~')
  74. uni.removeStorageSync('token')
  75. uni.navigateTo({url:'/pages/login/login'})
  76. return;
  77. // setTimeout(()=>{
  78. // //已有提示
  79. // uni.redirectTo({
  80. // url:'/pages/index/loginMobile'
  81. // })
  82. // },1200)
  83. }
  84. Tools.msg(error.statusCode+' '+(error.data.msg|| '请求失败~'))
  85. }else{
  86. Tools.msg('请求失败~')
  87. }
  88. return error;
  89. })
  90. return request.request({
  91. url: api.url,
  92. data,
  93. method: api.method,
  94. isNprogress: isNeedLoading || api.isNprogress,
  95. header: api.header,
  96. })
  97. }
  98. function getApiObj(url) {
  99. let apiArray = url.split(".");
  100. let api = apiList;
  101. apiArray.forEach(v => {
  102. api = api[v];
  103. });
  104. return api;
  105. }
  106. function getCacheKey(k, url,data={}){
  107. // mydate.getDay()+ mydate.getHours()+ mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds()+ Math.round(Math.random() * 10000);
  108. const key = k ? k : url;
  109. return "cache-"+key+JSON.stringify(data)
  110. }