uni_request.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import {CancelToken,Cancel,isCancel} from './cancel.js'
  2. class Request {
  3. constructor(args) {
  4. this.defaults = {headers:{'Accept': 'application/json',
  5. 'Content-Type': 'application/x-www-form-urlencoded'},debug:false,...args} || {};
  6. this.timer = null;
  7. this.requestTask = null;
  8. this.aborted = false;
  9. this.timeoutCancel = false;
  10. this.Cancel = Cancel;
  11. this.CancelToken = CancelToken;
  12. this.isCancel = isCancel;
  13. }
  14. interceptors = { // 拦截器
  15. request: {
  16. interceptors: [],
  17. use(fn) {
  18. this.interceptors.push(fn)
  19. },
  20. async intercept(config) {
  21. for (let i = 0; i < this.interceptors.length; i++) {
  22. config = await this.interceptors[i](config)
  23. }
  24. return config
  25. }
  26. },
  27. response: {
  28. interceptors: [],
  29. use(fn) {
  30. this.interceptors.push(fn)
  31. },
  32. async intercept(resolve, response) {
  33. for (let i = 0; i < this.interceptors.length; i++) {
  34. response = await this.interceptors[i](response)
  35. }
  36. return resolve(response)
  37. }
  38. }
  39. }
  40. abort = () => {
  41. this.aborted = true;
  42. this.requestTask ? this.requestTask.abort() : ''
  43. }
  44. onerror = async (options={...args}) => {
  45. let obj = {
  46. url: options.url,
  47. method: options.method,
  48. mes: options.str
  49. };
  50. if(options.cancel){
  51. obj.mes=options.cancel.message || '取消请求'
  52. }
  53. if(this.defaults.debug){
  54. console.log(obj.mes, options)
  55. }
  56. return obj;
  57. }
  58. request(options) {
  59. const _this = this;
  60. let {method, url, data,cancelToken} = options;
  61. let config = {
  62. url: this.defaults.baseURL + url,
  63. method: method.toUpperCase() || 'GET',
  64. header: this.defaults.headers || {},
  65. data: data || {},
  66. }
  67. return new Proxy(new Promise((resolve, reject) => {
  68. _this.interceptors.request.intercept(config).then(async (res) => {
  69. if (_this.aborted) { // 如果请求已被取消,停止执行,返回 reject
  70. const str = '主动中断请求';
  71. await _this.onerror({config,str})
  72. return reject(str)
  73. }
  74. if (config.cancelToken) {
  75. // Handle cancellation
  76. config.cancelToken.promise.then(async function onCanceled(cancel) {
  77. clearTimeout(_this.timer)
  78. _this.requestTask = null;
  79. await _this.onerror({config, cancel})
  80. return reject(cancel);
  81. });
  82. }
  83. _this.requestTask = uni.request({
  84. ...config,
  85. success: async (res) => {
  86. clearTimeout(_this.timer) // 清除检测超时定时器
  87. _this.interceptors.response.intercept(resolve, res) // 执行响应拦截器
  88. },
  89. fail: async (error) => {
  90. console.log(error)
  91. clearTimeout(_this.timer) // 清除检测超时定时器
  92. let failTimer = setTimeout(async () => {
  93. // 区分失败原因为超时或其它原因
  94. const str = '网络异常或URL无效'
  95. if (!_this.timeoutCancel) {
  96. await _this.onerror({config, str})
  97. clearTimeout(failTimer)
  98. reject(str)
  99. }
  100. }, 300)
  101. }
  102. });
  103. _this.timer = setTimeout(async () => { // 请求超时执行方法
  104. if (config.cancelToken) {return}
  105. _this.requestTask.abort(); // 执行取消请求方法
  106. _this.timeoutCancel = true;
  107. const str = `网络请求时间超时,当前设置响应时间为${_this.defaults.timeout}`
  108. await _this.onerror({config, str})
  109. reject(str)
  110. }, _this.defaults.timeout || 12345) // 设定检测超时定时器
  111. })
  112. }), {
  113. get: function(target, key, receiver) {
  114. // console.log(`getting ${key}!`);
  115. return key === 'abort' ? _this.abort : Reflect.get(target, key, receiver).bind(target); //传入target 为异步函数需要 .bind(target)
  116. },
  117. set: function(target, key, value, receiver) {
  118. // console.log(`setting ${key}!`);
  119. return Reflect.set(target, key, value, receiver);
  120. }
  121. })
  122. }
  123. }
  124. // class CreateInstance extends Request {
  125. // constructor(args) {
  126. // super();
  127. // super.defaults = args;
  128. // }
  129. // }
  130. let unirequest = new Request();
  131. unirequest.create = function(args) {
  132. return new Request(args)
  133. }
  134. export default unirequest;