js-xfetch
Version:
A Fetch request tool wrapper, convenient global management.
2 lines (1 loc) • 14.5 kB
JavaScript
var xfetch=function(t){"use strict";var e,n,r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function o(t,e,n,r){return new(n||(n=Promise))((function(o,i){function s(t){try{u(r.next(t))}catch(t){i(t)}}function a(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}u((r=r.apply(t,e||[])).next())}))}function i(t,e){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function s(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}t.XFetchContentType=void 0,(e=t.XFetchContentType||(t.XFetchContentType={})).JSON="application/json;charset=UTF-8",e.FORM="application/x-www-form-urlencoded;charset=UTF-8",e.FILE="multipart/form-data",e.json="application/json;charset=UTF-8",e.form="application/x-www-form-urlencoded;charset=UTF-8",e.file="multipart/form-data",t.XFetchHttpMethod=void 0,(n=t.XFetchHttpMethod||(t.XFetchHttpMethod={})).GET="GET",n.POST="POST",n.PUT="PUT",n.PATCH="PATCH",n.DELETE="DELETE",n.OPTIONS="OPTIONS",n.get="GET",n.post="POST",n.put="PUT",n.patch="PATCH",n.delete="DELETE",n.options="OPTIONS";var a={200:"服务器成功返回请求的数据。",201:"新建或修改数据成功。",202:"一个请求已经进入后台排队(异步任务)。",204:"删除数据成功。",301:"资源永久移动,请求的资源已被永久的移动到新 URI,返回信息会包括新的 URI,浏览器会自动定向到新 URI。",302:"资源临时移动,只是临时被移动,客户端可继续使用原有 URI。",303:"查看其它地址,与 301 类似,使用 GET 和 POST 请求查看。",304:"资源未修改,所请求的资源未修改,服务器返回此状态码时,不会返回任何资源。客户端通常会缓存访问过的资源,通过提供一个头信息指出客户端希望只返回在指定日期之后修改的资源。",400:"发出的请求有错误,服务器没有进行新建或修改数据的操作。",401:"用户没有权限(令牌、用户名、密码错误)。",403:"用户得到授权,但是访问是被禁止的。",404:"发出的请求针对的是不存在的记录,服务器没有进行操作。",406:"请求的格式不可得。",410:"请求的资源被永久删除,且不会再得到的。",422:"当创建一个对象时,发生一个验证错误。",500:"服务器发生错误,请检查服务器。",502:"网关错误。",503:"服务不可用,服务器暂时过载或维护。",504:"网关超时。"},u=function(){function e(t){var e,n,r,s,a,u,l,c,d,h=this;return this.timeout=3e4,this.baseUrl="",this._abortController=new AbortController,this._whiteListAbortController=new AbortController,this._handleFetchResponse=function(t){return o(h,void 0,void 0,(function(){var e,n,r;return i(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._parseFetchResponse(t)];case 1:return e=o.sent(),t.ok?[2,e]:(n=e,[2,Promise.reject(n)]);case 2:return r=o.sent(),[2,Promise.reject(r)];case 3:return[2]}}))}))},this._parseFetchResponse=function(t){return o(h,void 0,void 0,(function(){var e;return i(this,(function(n){switch(n.label){case 0:return(e=t.headers.get("Content-Type"))?e.includes("json")?[4,t.json()]:[3,2]:[3,10];case 1:case 3:case 5:case 7:case 9:case 11:return[2,n.sent()];case 2:return e.includes("text")?[4,t.text()]:[3,4];case 4:return e.includes("form")?[4,t.formData()]:[3,6];case 6:return e.includes("video")||e.includes("image")?[4,t.blob()]:[3,8];case 8:return e.includes("arrayBuffer")?[4,t.arrayBuffer()]:[3,10];case 10:return[4,t.text()]}}))}))},this._timeoutPromise=function(t,e){return new Promise((function(n,r){setTimeout((function(){n(new Response("timeout",{status:504,statusText:"timeout "})),null==e||e.abort()}),t)}))},this._cancelDuplicatedRequest=null===(e=null==t?void 0:t.cancelDuplicatedRequest)||void 0===e||e,this._cancelDuplicatedRequest&&(this._pendingRequests=new Map),this._requestHandler=null!==(n=null==t?void 0:t.requestHandler)&&void 0!==n?n:void 0,this._responseHandler=null!==(r=null==t?void 0:t.responseHandler)&&void 0!==r?r:void 0,this._errorHandler=null!==(s=null==t?void 0:t.errorHandler)&&void 0!==s?s:void 0,this._requestFinally=null!==(a=null==t?void 0:t.requestFinally)&&void 0!==a?a:void 0,this._setRequestHeaders=null!==(u=null==t?void 0:t.setRequestHeaders)&&void 0!==u?u:void 0,this._retryConfig=null!==(l=null==t?void 0:t.retryConfig)&&void 0!==l?l:void 0,this.timeout=null!==(c=null==t?void 0:t.timeout)&&void 0!==c?c:this.timeout,this.baseUrl=null!==(d=null==t?void 0:t.baseUrl)&&void 0!==d?d:this.baseUrl,this}return e.prototype._requestInterceptor=function(t){var e;if(null===(e=this._requestHandler)||void 0===e||e.call(this,t),this._cancelDuplicatedRequest&&!t.abortController)return this._removePendingRequest(t),this._addPendingRequest(t)},e.prototype._responseInterceptor=function(t){var e;this._cancelDuplicatedRequest&&!t.abortController&&this._removePendingRequest(t),null===(e=this._responseHandler)||void 0===e||e.call(this,t)},e.prototype._errorInterceptor=function(t){var e;return this.isCancel(t.error)||(this._cancelDuplicatedRequest&&this._pendingRequests.clear(),this._whiteListAbortController=new AbortController,this._abortController=new AbortController),null===(e=this._errorHandler)||void 0===e?void 0:e.call(this,t)},e.prototype._addPendingRequest=function(t){var e=[t.method,t.url,JSON.stringify(t.params),JSON.stringify(t.data)].join("&"),n=new AbortController;return this._pendingRequests.has(e)||this._pendingRequests.set(e,n),n},e.prototype._removePendingRequest=function(t){var e=[t.method,t.url,JSON.stringify(t.params),JSON.stringify(t.data)].join("&");this._pendingRequests.has(e)&&(this._pendingRequests.get(e).abort(e),this._pendingRequests.delete(e))},e.prototype.typeof=function(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()},e.prototype.qsStringify=function(t,e){var n=this;if(!t)return"";var r=new URLSearchParams;return Object.keys(t).forEach((function(o){var i=t[o];switch(n.typeof(i)){case"object":Object.keys(i).forEach((function(t){r.append("".concat(o,"[").concat(t,"]"),"object"==n.typeof(i[t])?JSON.stringify(i[t]):i[t])}));break;case"array":(null==e?void 0:e.arr2str)?r.append(o,i.join(",")):i.filter(Boolean).forEach((function(t,i){var s="object"==n.typeof(t)?JSON.stringify(t):t;(null==e?void 0:e.hasBrackets)?r.append((null==e?void 0:e.hasIndex)?"".concat(o,"[").concat(i,"]"):"".concat(o,"[]"),s):r.append(o,s)}));break;default:r.append(o,i)}})),(null==e?void 0:e.urlEncode)?r.toString():decodeURIComponent(r.toString())},e.prototype.qsParse=function(t,e){var n=null!=t?t:window.location.pathname;t=null!=t?t:window.location.search;var r=n.substring(n.lastIndexOf("/")+1),o={"/":null!=r?r:void 0},i=0===t.indexOf("?")?t.substring(1):t;if(0!==i.length)for(var s=i.split("&"),a=0;a<s.length;a++){var u=s[a].split("="),l=decodeURIComponent(u[0]),c=decodeURIComponent(u[1]);o[l]?(!Array.isArray(o[l])&&(o[l]=Array(o[l])),o[l].push(c)):o[l]=c}return e?null==o?void 0:o[e]:o},e.prototype.request=function(e,n,s,a){var u,l,c,d,h,p;return void 0===a&&(a=!1),o(this,void 0,void 0,(function(){var f,v,y,b,m,g,_,T,w,C,q=this;return i(this,(function(R){if(f=s.autoContentType||void 0===s["Content-Type"]?e===t.XFetchHttpMethod.POST?t.XFetchContentType.FORM:t.XFetchContentType.JSON:s["Content-Type"],v=n.includes("://")?n:(this.baseUrl+n).replace(/([^\:])\/\//g,"$1/"),s.params&&(v+="".concat(v.includes("?")?"&":"?").concat(this.qsStringify(s.params,null!==(u=s.qsStringifyOptions)&&void 0!==u?u:{}))),this._cancelDuplicatedRequest&&!a||(a?(y=this._whiteListAbortController,b=this._whiteListAbortController.signal):(y=this._abortController,b=this._abortController.signal)),m=new Headers(r(r({"Content-Type":f},null!==(l=s.headers)&&void 0!==l?l:{}),null!==(d=null===(c=this._setRequestHeaders)||void 0===c?void 0:c.call(this,s))&&void 0!==d?d:{})),g={config:s,headers:m,url:v,path:n,method:e,abortController:y},(_=null===(h=this._requestInterceptor)||void 0===h?void 0:h.call(this,g))&&!b&&(b=_.signal,y=_),e&&e!==t.XFetchHttpMethod.GET)if(e===t.XFetchHttpMethod.POST&&f===t.XFetchContentType.FORM){if(w=void 0,"string"===this.typeof(s.data))w=s.data;else{if("object"!==this.typeof(s.data))throw new Error("body must be string or object");w=this.qsStringify(s.data,null!==(p=s.qsStringifyOptions)&&void 0!==p?p:{})}T={body:w,headers:m,signal:b,method:t.XFetchHttpMethod.POST}}else T={body:JSON.stringify(s.data),headers:m,signal:b,method:e};else T={headers:m,signal:b};return C=function(t){var e=t?(q.timeout+t.delay+500)*(t.retry?t.retry:1):q.timeout;return Promise.race([q._timeoutPromise(e,y),fetch(v,T)]).then((function(t){return q.checkStatus(t)})).then((function(t){return q._handleFetchResponse(t)})).then((function(t){return o(q,void 0,void 0,(function(){var e,n;return i(this,(function(o){return e=r(r({},g),{data:t}),null===(n=this._responseInterceptor)||void 0===n||n.call(this,e),[2,t]}))}))})).catch((function(e){return o(q,void 0,void 0,(function(){var n,o;return i(this,(function(i){switch(i.label){case 0:return n=r(r({},g),{error:e}),t&&t.retry>0&&!this.isCancel(e)?[4,this.sleep(t.delay)]:[3,2];case 1:return i.sent(),[2,C(r(r({},t),{retry:t.retry-1}))];case 2:return[2,null===(o=this._errorInterceptor)||void 0===o?void 0:o.call(this,n)]}}))}))})).finally((function(){var t;null===(t=q._requestFinally)||void 0===t||t.call(q)}))},[2,C(this._retryConfig)]}))}))},e.prototype.sleep=function(t){return new Promise((function(e){return setTimeout(e,t)}))},e.prototype.checkStatus=function(t){var e=t.status;if(e>=200&&e<300)return t;var n=a[e]||t.statusText,r=new Error(n);return r.name=t.status,r.response=t,Promise.reject(r)},e.prototype.get=function(e,n,s,a){return void 0===n&&(n={}),void 0===s&&(s={}),void 0===a&&(a=!1),o(this,void 0,void 0,(function(){return i(this,(function(o){return[2,this.request(t.XFetchHttpMethod.GET,e,r({params:n},s),a)]}))}))},e.prototype.post=function(e,n,s,a){return void 0===n&&(n={}),void 0===s&&(s={}),void 0===a&&(a=!1),o(this,void 0,void 0,(function(){return i(this,(function(o){return[2,this.request(t.XFetchHttpMethod.POST,e,r({data:n},s),a)]}))}))},e.prototype.patch=function(e,n,s,a){return void 0===n&&(n={}),void 0===s&&(s={}),void 0===a&&(a=!1),o(this,void 0,void 0,(function(){return i(this,(function(o){return[2,this.request(t.XFetchHttpMethod.PATCH,e,r({data:n},s),a)]}))}))},e.prototype.put=function(e,n,s,a){return void 0===n&&(n={}),void 0===s&&(s={}),void 0===a&&(a=!1),o(this,void 0,void 0,(function(){return i(this,(function(o){return[2,this.request(t.XFetchHttpMethod.PUT,e,r({data:n},s),a)]}))}))},e.prototype.delete=function(e,n,s,a){return void 0===n&&(n={}),void 0===s&&(s={}),void 0===a&&(a=!1),o(this,void 0,void 0,(function(){return i(this,(function(o){return[2,this.request(t.XFetchHttpMethod.DELETE,e,r({data:n},s),a)]}))}))},e.prototype.postForm=function(e,n,s,a){return void 0===n&&(n={}),void 0===s&&(s={}),void 0===a&&(a=!1),o(this,void 0,void 0,(function(){return i(this,(function(o){return[2,this.request(t.XFetchHttpMethod.POST,e,r(r({"Content-Type":t.XFetchContentType.FORM},s),{data:n}),a)]}))}))},e.prototype.postFile=function(e,n,s,a,u,l,c){return void 0===s&&(s="file"),void 0===a&&(a=!1),void 0===u&&(u=!1),void 0===l&&(l={}),void 0===c&&(c=!1),o(this,void 0,void 0,(function(){var o;return i(this,(function(i){return o=new FormData,Array.isArray(n)?n.forEach((function(t,e){a?o.append(u?"".concat(s,"[]"):"".concat(s,"[").concat(e,"]"),t):o.append(s,t)})):o.append(s,n),[2,this.request(t.XFetchHttpMethod.POST,e,r(r({"Content-Type":t.XFetchContentType.FILE},l),{data:o}),c)]}))}))},e.prototype.cancelRequest=function(t){var e,n,r;if(this._cancelDuplicatedRequest){try{for(var o=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(this._pendingRequests),i=o.next();!i.done;i=o.next()){var a=s(i.value,2),u=a[0];(0,a[1])(t?"".concat(t,": ").concat(u):u)}}catch(t){e={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(e)throw e.error}}this._pendingRequests.clear()}else null===(r=this._abortController)||void 0===r||r.abort(t),this._abortController=new AbortController;return this},e.prototype.cancelWhiteListRequest=function(t){var e;return null===(e=this._whiteListAbortController)||void 0===e||e.abort(t),this._whiteListAbortController=new AbortController,this},e.prototype.getAbortController=function(){return new AbortController},e.prototype.getBaseURL=function(){return this.baseUrl},e.prototype.setBaseURL=function(t){return this.baseUrl=null!=t?t:"",this},e.prototype.setRequestTimeout=function(t){return this.timeout=t,this},e.prototype.getInstance=function(){return this},e.prototype.isCancel=function(t){return"AbortError"===t.name},e.prototype.create=function(t){return new e(t)},e}(),l=new u;return t.CODE_MSG=a,t.XFetch=l,t.XFetchClass=u,t.default=l,Object.defineProperty(t,"__esModule",{value:!0}),t}({});