UNPKG

lch-request

Version:

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

5 lines (3 loc) 16.8 kB
var j=Object.defineProperty,K=Object.defineProperties;var G=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,u=(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},S=(t,e)=>K(t,G(e));var p=(t,e,r)=>new Promise((a,n)=>{var s=h=>{try{i(r.next(h));}catch(l){n(l);}},o=h=>{try{i(r.throw(h));}catch(l){n(l);}},i=h=>h.done?a(h.value):Promise.resolve(h.value).then(s,o);i((r=r.apply(t,e)).next());});var w=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,n)=>p(this,null,function*(){if(!e){n({code:1,msg:"\u6587\u4EF6\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A",data:void 0});return}let s=r||this.uploadDir;s||n({code:1,msg:"\u4E0A\u4F20\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A",data:void 0}),this.uploadImageUrl||n({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 o=P(e)?e.split(".").pop():"png",i=`${Date.now()}_${Math.floor(Math.random()*1e6)}.${o}`,h=`${this.uploadImageUrl}/${s}/${i}`,l=u(u({key:`${s}/${i}`,success_action_status:200},yield this.getUploadParams()),this.formData),y=uni.uploadFile({url:this.uploadImageUrl,filePath:e,name:"file",formData:u({},l),fail:m=>{if(m.statusCode!==200){n({code:1,msg:"\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",data:m.data});return}}});a({code:0,msg:"success",data:{uploadTask:y,url:h,path:`/${s}/${i}`}});}))}},U=w;var A=t=>{var e,r,a,n,s,o,i,h,l,y,m,T,c,f,g,b,d,C,R,k,q,x,E,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:(n=t.loadingText)!=null?n:"\u8BF7\u6C42\u4E2D...",before:t.before,after:t.after,header:(s=t.header)!=null?s:{},timeout:(o=t.timeout)!=null?o:60*1e3,method:(i=t.method)!=null?i:"GET",dataType:(h=t.dataType)!=null?h:"json",responseType:(l=t.responseType)!=null?l:"text",sslVerify:(y=t.sslVerify)!=null?y:!0,withCredentials:(m=t.withCredentials)!=null?m:!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:(g=t.tokenStorageKeyName)!=null?g:"",taskIdValue:t.taskIdValue,tokenValue:t.tokenValue,buildQueryString:t.buildQueryString,takeTokenMethod:(b=t.takeTokenMethod)!=null?b:"header",takenTokenKeyName:(d=t.takenTokenKeyName)!=null?d:"Authorization",autoRefreshToken:!1,refreshTokenHandle:t.refreshTokenHandle,tokenExpiredCode:(C=t.tokenExpiredCode)!=null?C:403,tokenExpiredCodeType:(R=t.tokenExpiredCodeType)!=null?R:"httpStatusCode",retry:(k=t.retry)!=null?k:!1,retryCount:(q=t.retryCount)!=null?q:3,retryCountAutoOffRetry:(x=t.retryCountAutoOffRetry)!=null?x:!0,retryMaximum:(E=t.retryMaximum)!=null?E:64,retryDeadline:(I=t.retryDeadline)!=null?I:1e4,loadingStartTime:(N=t.loadingStartTime)!=null?N:0}},D=t=>{var e,r,a,n,s,o,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:(n=t==null?void 0:t.dataType)!=null?n:"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:(o=t==null?void 0:t.retryCount)!=null?o: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 B=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 O(t,e,r){let a,n=(l,y="",m)=>{r.errorHandleByCode&&r.errorHandleByCode(l,y,m);};return {request:(l,y)=>{var g,b,d,C,R;r.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42\u62E6\u622A:${JSON.stringify(l)}`);let m=(g=e.loading)!=null?g:r.loading,T=(b=e.loadingText)!=null?b:r.loadingText;m&&(a=setTimeout(()=>{B({title:T!=null?T:"\u8BF7\u6C42\u4E2D..."});},r.loadingStartTime)),(d=l==null?void 0:l.header)!=null&&d.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||((R=e.url)==null?void 0:R.indexOf("https://"))>-1)&&(f=e.url),l.method==="GET")if(r.buildQueryString){let k=r.buildQueryString(l.data);k==="false"?l.url=f:(l.data=k||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,y)),t.request(l)},response:(l,y)=>(a&&clearTimeout(a),n(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,y)),l),fail:l=>(a&&clearTimeout(a),l.errMsg==="request:fail"?uni.getNetworkType({success:y=>{y.networkType==="none"?n(1009,l.errMsg):n(-1,JSON.stringify(l));},fail:()=>{n(-1,JSON.stringify(l));}}):l.errMsg==="request:fail timeout"?n(408,l.errMsg):n(404,l.errMsg),r.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42\u62E6\u622A\u5931\u8D25:${JSON.stringify(l)}`),l),complete:l=>{var m;a&&clearTimeout(a),((m=e.loading)!=null?m: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 v=class{constructor(e){this._task=e;}abort(){this._task&&(this._task.abort(),this._task=null);}};function X(t){let e={},r,a,n;return t&&t.split(` `).forEach(s=>{n=s.indexOf(":"),r=s.substr(0,n).trim().toLowerCase(),a=s.substr(n+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,n=new v(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,n.abort();let i={errMsg:"request:fail timeout"};t.fail&&t.fail(i);},t.timeout)),a.responseType=t.dataType||"text";let o={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(o);},a.onabort=()=>{s&&clearTimeout(s);let i={errMsg:"request:fail abort"};t.fail&&t.fail(i),t.complete&&t.complete(o);},a.onerror=()=>{s&&clearTimeout(s);let i={errMsg:"request:fail"};t.fail&&t.fail(i),t.complete&&t.complete(o);},a.onloadend=()=>{t.complete&&t.complete(o);},a.withCredentials=t.withCredentials||!1,a.send(t.data),n}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.retryTokenRefreshCount=0;this.maxTokenRefreshRetry=1;this.globalConfig={baseUrl:{pro:"",dev:""},errorHandleByCode:(e,r,a)=>{},apiErrorInterception:(e,r,a)=>{}};this.reqConfig={};if(this.globalConfig=u({},A(e)),this.reqConfig=u({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,n=""){var i,h;let s=uni.getStorageSync(this.requestTasksName),o=(i=r==null?void 0:r.task_id)!=null?i:"";return this.globalConfig.taskIdValue&&(o=yield this.globalConfig.taskIdValue(e,r)),o&&s[o]&&(this.globalConfig.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u8BF7\u6C42ID${o}\u6709\u91CD\u590D\u9879\u5DF2\u81EA\u52A8\u8FC7\u6EE4`),(h=s[o])==null||h.abort()),new Promise((l,y)=>p(this,null,function*(){let m=uni.getStorageSync(this.globalConfig.tokenStorageKeyName);(()=>new Promise((c,f)=>p(this,null,function*(){m&&c(m);let g="";this.globalConfig.tokenValue&&(g=yield this.globalConfig.tokenValue()),a&&this.globalConfig.refreshTokenHandle?this.globalConfig.refreshTokenHandle(g).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,g;typeof c=="string"&&r&&r.autoTakeToken&&(this.globalConfig.takeTokenMethod==="header"&&(r.header=(f=r.header)!=null?f:{},r.header[(g=this.globalConfig)==null?void 0:g.takenTokenKeyName]=c),this.globalConfig.takeTokenMethod==="body"&&(e[this.globalConfig.takenTokenKeyName]=c)),l(!0);});}))})}request(e,r={},a,n=null){var o;let s=u(u({autoTakeToken:(a==null?void 0:a.autoTakeToken)||((o=D(a))==null?void 0:o.autoTakeToken)},this.reqConfig),a);return new Promise((i,h)=>{var l,y,m,T;this.beforeRequest(r,S(u({},s),{baseUrl:{dev:(y=s.domain)!=null?y:(l=this.globalConfig)==null?void 0:l.baseUrl.dev,pro:(T=s.domain)!=null?T:(m=this.globalConfig)==null?void 0:m.baseUrl.pro}}),n,e).then(()=>p(this,null,function*(){var b;let c=O({request:d=>(e=d.url,s=S(u(u({},this.reqConfig),d),{header:u(u({},this.reqConfig.header),d==null?void 0:d.header)}),d),response:d=>d,fail:d=>(h(d),d)},u({url:e},s),S(u({},this.globalConfig),{baseUrl:{dev:s.domain||this.globalConfig.baseUrl.dev,pro:s.domain||this.globalConfig.baseUrl.pro}})),f=()=>{this.currentRequestTask=$({url:e,data:u(u({},r),s.data||{}),header:u({},s.header),method:s.method,timeout:s.timeout,dataType:s.dataType,responseType:s.responseType,sslVerify:s.sslVerify,withCredentials:s.withCredentials,firstIpv4:s.firstIpv4,success:d=>{var k;let C=d.statusCode;if(((k=this.globalConfig)==null?void 0:k.tokenExpiredCodeType)==="apiResponseCode"&&typeof this.globalConfig.tokenExpiredCode!==void 0&&this.globalConfig.xhrCodeName&&(C=d.data[this.globalConfig.xhrCodeName]),C===this.globalConfig.tokenExpiredCode){if(this.retryTokenRefreshCount>=this.maxTokenRefreshRetry){h("\u8FBE\u5230\u6700\u5927token\u5237\u65B0\u91CD\u8BD5\u6B21\u6570");return}if(this.retryTokenRefreshCount++,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(q=>{var x;this.globalConfig.debug&&console.warn(`\u3010LwuRequest Debug\u3011\u65B0\u7684token:${q}`),q&&s.header&&(s.header[(x=this.globalConfig)==null?void 0:x.takenTokenKeyName]=q),f();}).catch(()=>{h(d);});return}}if(n){n(d.data);return}let R=this.globalConfig.after?c.response(d,h):a.originalResponse?d:d.data;i(R);},fail:d=>{var C;c.fail(d),this.retryCount=(C=s.retryCount)!=null?C:3,this.retryCount&&(this.retryCount--,setTimeout(f,this.retryTimeout.shift()),this.globalConfig.networkExceptionHandle&&this.globalConfig.networkExceptionHandle()),h(d);},complete:d=>{c.complete(d);}},this.globalConfig.env);};f();let g=(b=s==null?void 0:s.task_id)!=null?b:"";if(this.globalConfig.taskIdValue&&(g=yield this.globalConfig.taskIdValue(r,a)),g){let d=[];d[g]=this.currentRequestTask,uni.setStorageSync(this.requestTasksName,d);}}));})}get(e,r={},a={}){return this.request(e,r,u({method:"GET"},a))}post(e,r={},a={}){return this.request(e,r,u({method:"POST"},a))}put(e,r={},a={}){return this.request(e,r,u({method:"PUT"},a))}delete(e,r={},a={}){return this.request(e,r,u({method:"DELETE"},a))}config(e={}){return this.reqConfig=u(S(u({},this.globalConfig),{autoTakeToken:e.autoTakeToken||D(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=u({},e),this}abort(e=""){let r=uni.getStorageSync(this.requestTasksName);r[e]?r[e].abort():this.currentRequestTask.abort();}download(e){var s;let r=S(u(u({},this.reqConfig),e),{method:"DOWNLOAD"}),a=O({request:o=>(e.url=o.url,o),response:o=>o},u({},r),this.globalConfig),n=u({contentType:""},r==null?void 0:r.header);return a.request({header:n,method:"DOWNLOAD",data:"",url:e.url,customData:{}}),uni.downloadFile({url:e.url,header:n,timeout:(s=r.timeout)!=null?s:6e4,filePath:r.filePath,success:o=>{a.response(S(u({},o),{data:"",header:{},cookies:[]})),e.success&&e.success(o);},fail:o=>{a.fail(o),e.fail&&e.fail(o);},complete:o=>{a.complete(o),e.complete&&e.complete(o);}})}upload(e){let r=S(u(u({},this.reqConfig),e),{method:"UPLOAD"}),a=O({request:s=>(e.url=s.url,s),response:s=>s},u({},r),this.globalConfig),n=u({contentType:""},r==null?void 0:r.header);return a.request({header:n,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:n,timeout:e.timeout,formData:e.formData,success:s=>{a.response(S(u({},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 U({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 U({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));}}; export { H as Http };