UNPKG

lwu-request

Version:

基于uniapp网络请求API封装的轻量级网络请求库,支持自动刷新token,请求拦截,请求中断,自动重试等特性

7 lines (4 loc) 17.5 kB
'use strict'; var j=Object.defineProperty,G=Object.defineProperties;var K=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var V=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var _=(t,e,r)=>e in t?j(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,d=(t,e)=>{for(var r in e||(e={}))V.call(e,r)&&_(t,r,e[r]);if(M)for(var r of M(e))F.call(e,r)&&_(t,r,e[r]);return t},k=(t,e)=>G(t,K(e));var p=(t,e,r)=>new Promise((a,o)=>{var s=h=>{try{i(r.next(h));}catch(l){o(l);}},u=h=>{try{i(r.throw(h));}catch(l){o(l);}},i=h=>h.done?a(h.value):Promise.resolve(h.value).then(s,u);i((r=r.apply(t,e)).next());});var x=class{constructor(e){this.options=e,this.timeout=(e==null?void 0:e.timeout)||1,this.maxSize=(e==null?void 0:e.maxSize)||5*1024*1024,this.securityToken="",this.accessKeyId="",this.accessKeySecret="",this.uploadDir=(e==null?void 0:e.uploadDir)||"",this.uploadImageUrl=(e==null?void 0:e.uploadImageUrl)||"",this.formData=(e==null?void 0:e.formData)||{},this.getOSSBySTS=()=>e==null?void 0:e.getOSSBySTS(),this.getPolicyBase64=()=>e==null?void 0:e.getPolicyBase64();}getSignature(e,r,a){return p(this,null,function*(){return yield a==null?void 0:a.getSignature(e,r)})}getOSSBySTSInfo(){return p(this,null,function*(){let{access_key_id:e,access_key_secret:r,security_token:a}=yield this.getOSSBySTS();this.accessKeyId=e,this.accessKeySecret=r,this.securityToken=a;})}getUploadParams(){return p(this,null,function*(){let e=this.getPolicyBase64(),r=yield this.getSignature(e,this.accessKeySecret,this.options);return {OSSAccessKeyId:this.accessKeyId,policy:e,signature:r,"x-oss-security-token":this.securityToken}})}uploadFile(e,r){return new Promise((a,o)=>p(this,null,function*(){if(!e){o({code:1,msg:"\u6587\u4EF6\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A",data:void 0});return}let s=r||this.uploadDir;s||o({code:1,msg:"\u4E0A\u4F20\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A",data:void 0}),this.uploadImageUrl||o({code:1,msg:"\u4E0A\u4F20\u670D\u52A1\u5668\u57DF\u540D\u6216\u4E0A\u4F20\u7684\u963F\u91CC\u4E91OSS\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A",data:void 0});let u=P(e)?e.split(".").pop():"png",i=`${Date.now()}_${Math.floor(Math.random()*1e6)}.${u}`,h=`${this.uploadImageUrl}/${s}/${i}`,l=d(d({key:`${s}/${i}`,success_action_status:200},yield this.getUploadParams()),this.formData),m=uni.uploadFile({url:this.uploadImageUrl,filePath:e,name:"file",formData:d({},l),fail:g=>{if(g.statusCode!==200){o({code:1,msg:"\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",data:g.data});return}}});a({code:0,msg:"success",data:{uploadTask:m,url:h,path:`/${s}/${i}`}});}))}},O=x;var A=t=>{var e,r,a,o,s,u,i,h,l,m,g,T,c,f,y,b,n,C,S,R,D,E,v,I,N;return {baseUrl:t.baseUrl,debug:(e=t.debug)!=null?e:!1,env:(r=t.env)!=null?r:"uniapp",loading:(a=t.loading)!=null?a:!0,loadingText:(o=t.loadingText)!=null?o:"\u8BF7\u6C42\u4E2D...",before:t.before,after:t.after,header:(s=t.header)!=null?s:{},timeout:(u=t.timeout)!=null?u:60*1e3,method:(i=t.method)!=null?i:"GET",dataType:(h=t.dataType)!=null?h:"json",responseType:(l=t.responseType)!=null?l:"text",sslVerify:(m=t.sslVerify)!=null?m:!0,withCredentials:(g=t.withCredentials)!=null?g:!1,firstIpv4:(T=t.firstIpv4)!=null?T:!1,errorHandleByCode:t.errorHandleByCode,apiErrorInterception:t.apiErrorInterception,networkExceptionHandle:()=>{},xhrCode:t.xhrCode,xhrCodeName:(c=t.xhrCodeName)!=null?c:"code",requestSuccessResponseMsgName:(f=t.requestSuccessResponseMsgName)!=null?f:"msg",tokenStorageKeyName:(y=t.tokenStorageKeyName)!=null?y:"",taskIdValue:t.taskIdValue,tokenValue:t.tokenValue,buildQueryString:t.buildQueryString,takeTokenMethod:(b=t.takeTokenMethod)!=null?b:"header",takenTokenKeyName:(n=t.takenTokenKeyName)!=null?n:"Authorization",autoRefreshToken:!1,refreshTokenHandle:t.refreshTokenHandle,tokenExpiredCode:(C=t.tokenExpiredCode)!=null?C:403,tokenExpiredCodeType:(S=t.tokenExpiredCodeType)!=null?S:"httpStatusCode",retry:(R=t.retry)!=null?R:!1,retryCount:(D=t.retryCount)!=null?D:3,retryCountAutoOffRetry:(E=t.retryCountAutoOffRetry)!=null?E:!0,retryMaximum:(v=t.retryMaximum)!=null?v:64,retryDeadline:(I=t.retryDeadline)!=null?I:1e4,loadingStartTime:(N=t.loadingStartTime)!=null?N:0}},w=t=>{var e,r,a,o,s,u,i,h,l;return {task_id:(e=t==null?void 0:t.task_id)!=null?e:"",before:t==null?void 0:t.before,after:t==null?void 0:t.after,header:t==null?void 0:t.header,method:(r=t==null?void 0:t.method)!=null?r:"GET",timeout:(a=t==null?void 0:t.timeout)!=null?a:6e3,dataType:(o=t==null?void 0:t.dataType)!=null?o:"json",responseType:(s=t==null?void 0:t.responseType)!=null?s:"text",sslVerify:(t==null?void 0:t.sslVerify)||!1,withCredentials:(t==null?void 0:t.withCredentials)||!1,firstIpv4:(t==null?void 0:t.firstIpv4)||!1,retryCount:(u=t==null?void 0:t.retryCount)!=null?u:3,loading:(t==null?void 0:t.loading)||!0,loadingText:(i=t==null?void 0:t.loadingText)!=null?i:"\u8BF7\u6C42\u4E2D...",domain:(h=t==null?void 0:t.domain)!=null?h:"",autoTakeToken:(t==null?void 0:t.autoTakeToken)||!0,originalResponse:(t==null?void 0:t.originalResponse)||!1,customData:(l=t.customData)!=null?l:{}}};var L=t=>{uni.showLoading({title:t.title,mask:t.mask||!0});};var W=t=>typeof t=="object"&&t!==null?Object.keys(t).map(e=>`${e}=${encodeURIComponent(t[e])}`).join("&"):t;function q(t,e,r){let a,o=(l,m="",g)=>{r.errorHandleByCode&&r.errorHandleByCode(l,m,g);};return {request:(l,m)=>{var y,b,n,C,S;r.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42\u62E6\u622A:${JSON.stringify(l)}`);let g=(y=e.loading)!=null?y:r.loading,T=(b=e.loadingText)!=null?b:r.loadingText;g&&(a=setTimeout(()=>{L({title:T!=null?T:"\u8BF7\u6C42\u4E2D..."});},r.loadingStartTime)),(n=l==null?void 0:l.header)!=null&&n.contentType&&(l.header["content-type"]=l.header.contentType,delete l.header.contentType);let c="";process.env.NODE_ENV==="development"?c=r.baseUrl.dev:c=r.baseUrl.pro;let f=`${c}${e.url}`;if(e.url&&(((C=e.url)==null?void 0:C.indexOf("http://"))>-1||((S=e.url)==null?void 0:S.indexOf("https://"))>-1)&&(f=e.url),l.method==="GET")if(r.buildQueryString){let R=r.buildQueryString(l.data);R==="false"?l.url=f:(l.data=R||W(l.data),l.url=`${f}${l.data?`?${l.data}`:""}`);}else l.url=f;else l.url=f;return e.before&&e.before(l)&&(l=e.before(l,m)),t.request(l)},response:(l,m)=>(a&&clearTimeout(a),o(l.statusCode,l.data[r.requestSuccessResponseMsgName]),r.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u54CD\u5E94\u62E6\u622A:${JSON.stringify(l)}`),e.after&&(l=e.after(e.originalResponse?l:l.data,m)),l),fail:l=>(a&&clearTimeout(a),l.errMsg==="request:fail"?uni.getNetworkType({success:m=>{m.networkType==="none"?o(1009,l.errMsg):o(-1,JSON.stringify(l));},fail:()=>{o(-1,JSON.stringify(l));}}):l.errMsg==="request:fail timeout"?o(408,l.errMsg):o(404,l.errMsg),r.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42\u62E6\u622A\u5931\u8D25:${JSON.stringify(l)}`),l),complete:l=>{var g;a&&clearTimeout(a),((g=e.loading)!=null?g:r.loading)&&uni.hideLoading(),l.errMsg==="request:fail"&&r.networkExceptionHandle&&r.networkExceptionHandle(),r.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42\u62E6\u622A\u5B8C\u6210:${JSON.stringify(l)}`);}}}var P=t=>/\.(png|jpeg|jpg|webp|gif)$/i.test(t);var U=class{constructor(e){this._task=e;}abort(){this._task&&(this._task.abort(),this._task=null);}};function X(t){let e={},r,a,o;return t&&t.split(` `).forEach(s=>{o=s.indexOf(":"),r=s.substr(0,o).trim().toLowerCase(),a=s.substr(o+1).trim(),r&&(e[r]=e[r]?e[r]+", "+a:a);}),e}function Y(t={url:"",data:{},header:{},method:"GET",dataType:"json",responseType:"text",success:()=>{},fail:()=>{},complete:()=>{},timeout:0,withCredentials:!1}){console.log("\u5F53\u524D h5 \u8FD0\u884C\u73AF\u5883");let e="application/json";t.header&&Object.keys(t.header).forEach(i=>{i.toLowerCase()==="content-type"&&(e=t.header[i],e.indexOf("application/json")===0?e="json":e.indexOf("application/x-www-form-urlencoded")===0?e="urlencoded":e="string");}),t.method!=="GET"&&e!=="json"&&(e==="urlencoded"?t.data=Object.keys(t.data).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(t.data[i])}`).join("&"):e==="string"&&(t.data=t.data.toString()));let a=new XMLHttpRequest,o=new U(a);a.open(t.method,t.url,!0),t.header&&Object.keys(t.header).forEach(i=>{a==null||a.setRequestHeader(i,t.header[i]);});let s;t.timeout&&(s=setTimeout(()=>{a.onabort=null,o.abort();let i={errMsg:"request:fail timeout"};t.fail&&t.fail(i);},t.timeout)),a.responseType=t.dataType||"text";let u={errMsg:"request:ok"};return a.onload=()=>{if(s&&clearTimeout(s),(a==null?void 0:a.status)===200){let i=a.response;if(t.dataType==="json"&&typeof a.response=="string")try{i=JSON.parse(a.response);}catch(l){}let h={data:i,statusCode:a.status,header:X(a.getAllResponseHeaders()),errMsg:"request:ok",cookies:[]};t.success&&t.success(h);}else {let i={errMsg:`request:fail ${a==null?void 0:a.status}`};t.fail&&t.fail(i);}t.complete&&t.complete(u);},a.onabort=()=>{s&&clearTimeout(s);let i={errMsg:"request:fail abort"};t.fail&&t.fail(i),t.complete&&t.complete(u);},a.onerror=()=>{s&&clearTimeout(s);let i={errMsg:"request:fail"};t.fail&&t.fail(i),t.complete&&t.complete(u);},a.onloadend=()=>{t.complete&&t.complete(u);},a.withCredentials=t.withCredentials||!1,a.send(t.data),o}function Z(t,e="uniapp"){return e==="h5"?Y(t):e==="mp-weixin"?wx.request(t):uni.request(t)}var $=Z;var ee=(t,e)=>{let r=Math.floor(Math.random()*1e3);return Math.min(Math.pow(2,t)*1e3+r,e)};var H=class{constructor(e){this.currentRequestTask={abort:()=>{},onHeadersReceived:()=>{},offHeadersReceived:()=>{}};this.requestTasksName="LWU-REQUEST-TASKS";this.lock=!0;this.pending=[];this.retryCount=3;this.retryMaximum=64;this.retryTimeout=[];this.retryDeadline=1e4;this.globalConfig={baseUrl:{pro:"",dev:""},errorHandleByCode:(e,r,a)=>{},apiErrorInterception:(e,r,a)=>{}};this.reqConfig={};if(this.globalConfig=d({},A(e)),this.reqConfig=d({task_id:"",domain:""},this.globalConfig),!this.globalConfig.retry)this.retryCount=0;else if(this.globalConfig.retryCountAutoOffRetry){this.retryMaximum=this.globalConfig.retryMaximum*1e3,this.retryTimeout=[],this.retryDeadline=e.retryDeadline;for(let r=0;r<this.retryCount&&!(this.retryDeadline<0);r++){let a=ee(r,this.retryMaximum);this.retryDeadline-=a,this.retryTimeout.push(a);}this.retryCount=this.retryTimeout.length;}}handleError(e,r=""){this.globalConfig.errorHandleByCode&&this.globalConfig.errorHandleByCode(e,r);}refreshToken(){this.globalConfig.refreshTokenHandle&&this.globalConfig.refreshTokenHandle().then(()=>{uni.getStorageSync("LWU-REQUEST-CALLBACK")(e=>{e();});}).catch(()=>{this.handleError(this.globalConfig.tokenExpiredCode);});}beforeRequest(){return p(this,arguments,function*(e={},r,a=null,o=""){var i,h;let s=uni.getStorageSync(this.requestTasksName),u=(i=r==null?void 0:r.task_id)!=null?i:"";return this.globalConfig.taskIdValue&&(u=yield this.globalConfig.taskIdValue(e,r)),u&&s[u]&&(this.globalConfig.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42ID${u}\u6709\u91CD\u590D\u9879\u5DF2\u81EA\u52A8\u8FC7\u6EE4`),(h=s[u])==null||h.abort()),new Promise((l,m)=>p(this,null,function*(){let g=uni.getStorageSync(this.globalConfig.tokenStorageKeyName);(()=>new Promise((c,f)=>p(this,null,function*(){g&&c(g);let y="";this.globalConfig.tokenValue&&(y=yield this.globalConfig.tokenValue()),a&&this.globalConfig.refreshTokenHandle?this.globalConfig.refreshTokenHandle(y).then(b=>{b&&c(b),c(!1);}):this.globalConfig.tokenValue?this.globalConfig.tokenValue().then(b=>{b&&c(b),c(!1);}):c(!0);})))().then(c=>{var f,y;typeof c=="string"&&r&&r.autoTakeToken&&(this.globalConfig.takeTokenMethod==="header"&&(r.header=(f=r.header)!=null?f:{},r.header[(y=this.globalConfig)==null?void 0:y.takenTokenKeyName]=c),this.globalConfig.takeTokenMethod==="body"&&(e[this.globalConfig.takenTokenKeyName]=c)),l(!0);});}))})}request(e,r={},a,o=null){var u;let s=d(d({autoTakeToken:(a==null?void 0:a.autoTakeToken)||((u=w(a))==null?void 0:u.autoTakeToken)},this.reqConfig),a);return new Promise((i,h)=>{var l,m,g,T;this.beforeRequest&&this.beforeRequest(r,k(d({},s),{baseUrl:{dev:(m=s.domain)!=null?m:(l=this.globalConfig)==null?void 0:l.baseUrl.dev,pro:(T=s.domain)!=null?T:(g=this.globalConfig)==null?void 0:g.baseUrl.pro}}),o,e).then(()=>p(this,null,function*(){var y,b;let c=q({request:n=>(e=n.url,s=k(d(d({},this.reqConfig),n),{header:d(d({},this.reqConfig.header),n==null?void 0:n.header)}),n),response:n=>n,fail:n=>(h(n),n)},d({url:e},s),k(d({},this.globalConfig),{baseUrl:{dev:s.domain||this.globalConfig.baseUrl.dev,pro:s.domain||this.globalConfig.baseUrl.pro}}));c.request({header:d({},s.header),method:(y=a==null?void 0:a.method)!=null?y:"GET",customData:s.customData,data:r,url:e}),this.currentRequestTask=$({url:e,data:d(d({},r),s.data||{}),header:d({},s.header),method:s.method,timeout:s.timeout,dataType:s.dataType,responseType:s.responseType,sslVerify:s.sslVerify,withCredentials:s.withCredentials,firstIpv4:s.firstIpv4,success:n=>{var S;typeof this.globalConfig.xhrCode=="undefined"?this.globalConfig.apiErrorInterception&&this.globalConfig.apiErrorInterception(n.data,n,h):this.globalConfig.xhrCodeName&&n.data[this.globalConfig.xhrCodeName]!=="undefined"&&n.data[this.globalConfig.xhrCodeName]!==this.globalConfig.xhrCode&&(this.globalConfig.apiErrorInterception&&this.globalConfig.apiErrorInterception(n.data,n,h),h(n));let C=n.statusCode;if(((S=this.globalConfig)==null?void 0:S.tokenExpiredCodeType)==="apiResponseCode"&&typeof this.globalConfig.tokenExpiredCode!==void 0&&this.globalConfig.xhrCodeName&&(C=n.data[this.globalConfig.xhrCodeName]),o){this.globalConfig.debug&&console.warn(`\u3010LwuRequest Debug\u3011token\u5931\u6548\u4E8C\u6B21\u8BF7\u6C42\u6210\u529F\u54CD\u5E94:${JSON.stringify(n.data)}`),o(n.data);return}C!==this.globalConfig.tokenExpiredCode?this.globalConfig.after?i(c.response(n,h)):i(a.originalResponse?n:n.data):(this.globalConfig.debug&&console.warn("\u3010LwuRequest Debug\u3011token\u5931\u6548\uFF0C\u5F00\u59CB\u6267\u884C\u5237\u65B0token\u7A0B\u5E8F"),this.globalConfig.refreshTokenHandle&&this.globalConfig.refreshTokenHandle().then(R=>{this.globalConfig.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u65B0\u7684token:${R}`),this.globalConfig.debug&&console.warn("\u3010LwuRequest Debug\u3011\u81EA\u52A8\u5237\u65B0token\u5B8C\u6210\uFF0C\u5F00\u59CB\u91CD\u65B0\u53D1\u8D77\u8BF7\u6C42"),this.request(e,r,s,i);}));},fail:n=>{var C;c.fail(n),this.retryCount=(C=s.retryCount)!=null?C:3,this.retryCount&&(this.globalConfig.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u81EA\u52A8\u91CD\u8BD5\u6B21\u6570:${this.retryCount}`),this.retryCount--,setTimeout(this.request,this.retryTimeout.shift()),this.globalConfig.networkExceptionHandle&&this.globalConfig.networkExceptionHandle()),h(n);},complete:n=>{c.complete(n);}},this.globalConfig.env);let f=(b=s==null?void 0:s.task_id)!=null?b:"";if(this.globalConfig.taskIdValue&&(f=yield this.globalConfig.taskIdValue(r,a)),f){let n=[];n[f]=this.currentRequestTask,uni.setStorageSync(this.requestTasksName,n);}}));})}get(e,r={},a={}){return this.request(e,r,d({method:"GET"},a))}post(e,r={},a={}){return this.request(e,r,d({method:"POST"},a))}put(e,r={},a={}){return this.request(e,r,d({method:"PUT"},a))}delete(e,r={},a={}){return this.request(e,r,d({method:"DELETE"},a))}config(e={}){return this.reqConfig=d(k(d({},this.globalConfig),{autoTakeToken:e.autoTakeToken||w(e).autoTakeToken}),e),this}uri(){let e=this.reqConfig.domain||this.globalConfig.baseUrl.pro;return process.env.NODE_ENV==="development"&&(e=this.reqConfig.domain||this.globalConfig.baseUrl.dev),e}setHeader(e){return this.reqConfig.header=d({},e),this}abort(e=""){let r=uni.getStorageSync(this.requestTasksName);r[e]?r[e].abort():this.currentRequestTask.abort();}download(e){var s;let r=k(d(d({},this.reqConfig),e),{method:"DOWNLOAD"}),a=q({request:u=>(e.url=u.url,u),response:u=>u},d({},r),this.globalConfig),o=d({contentType:""},r==null?void 0:r.header);return a.request({header:o,method:"DOWNLOAD",data:"",url:e.url,customData:{}}),uni.downloadFile({url:e.url,header:o,timeout:(s=r.timeout)!=null?s:6e4,filePath:r.filePath,success:u=>{a.response(k(d({},u),{data:"",header:{},cookies:[]})),e.success&&e.success(u);},fail:u=>{a.fail(u),e.fail&&e.fail(u);},complete:u=>{a.complete(u),e.complete&&e.complete(u);}})}upload(e){let r=k(d(d({},this.reqConfig),e),{method:"UPLOAD"}),a=q({request:s=>(e.url=s.url,s),response:s=>s},d({},r),this.globalConfig),o=d({contentType:""},r==null?void 0:r.header);return a.request({header:o,method:"UPLOAD",data:"",url:e.url,customData:{}}),uni.uploadFile({url:e.url,files:e.files,fileType:e.fileType,file:e.file,filePath:e.filePath,name:e.name,header:o,timeout:e.timeout,formData:e.formData,success:s=>{a.response(k(d({},s),{data:"",header:{},cookies:[]})),e.success&&e.success(s);},fail:s=>{a.fail(s),e.fail&&e.fail(s);},complete:s=>{a.complete(s),e.complete&&e.complete(s);}})}uploadAliossSync(e){return p(this,null,function*(){let r=new O({filePath:e.filePath,uploadDir:e.uploadDir,maxSize:e.maxSize,uploadImageUrl:e.uploadImageUrl,getOSSBySTS:e.getOSSBySTS,getPolicyBase64:e.getPolicyBase64,getSignature:e.getSignature});return yield r.getOSSBySTSInfo(),yield r.uploadFile(e.filePath,e.uploadDir)})}uploadAlioss(e){let r=new O({filePath:e.filePath,uploadDir:e.uploadDir,maxSize:e.maxSize,uploadImageUrl:e.uploadImageUrl,getOSSBySTS:e.getOSSBySTS,getPolicyBase64:e.getPolicyBase64,getSignature:e.getSignature});r.getOSSBySTSInfo().then(()=>r.uploadFile(e.filePath,e.uploadDir));}}; exports.Http = H;