UNPKG

@magic_npm/simple-tools

Version:

`simple-tools` is a simple set of tools

3 lines (2 loc) 2.6 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SimpleTools={})}(this,function(e){"use strict";const t=function(e){const s=e();return[s,(a,n)=>{const r=n||!a?t.mergeData(e(),a):a;return t.mergeData(s,r)}]};t.getDataType=function(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()},t.mergeData=function(e,s){return e&&"object"===t.getDataType(e)&&["object","undefined"].includes(t.getDataType(s))&&s&&Object.keys(e).forEach(t=>{t in s&&(e[t]=s[t])}),e},e.useApi=function(e,s){const{isCancel:a,isRepeat:n,isSingle:r,loading:o,params:i,loadingStart:u,loadingEnd:l,before:c,success:p,error:d,inputModel:f,outputModel:m}={isCancel:!0,isRepeat:!0,isSingle:!1,...s},y={status:0,sendNum:{},sendLatestKey:void 0,pm:void 0,err:"",params:void 0,output:void 0,result:{res:void 0,data:void 0,loadingKey:""},cancelApi:async()=>{var e;const t=null==(e=y.pm)?void 0:e.cancel,s=Promise.resolve();if(t){null==t||t(),y.status=0;try{await y.pm}catch(a){}console.log("[cancel successful]")}else console.log("[cancel error] find not cancel function.");return s}};return[async(s,g="value")=>{let S;const v={};try{if(y.params=null==i?void 0:i(),y.params&&t.mergeData(y.params,s),"function"==typeof c){let e=c(y.params&&JSON.parse(JSON.stringify(y.params)));if(!1===e)throw"close send api.";e instanceof Promise&&await e}if(!n&&1===y.status)return Promise.reject("操作频繁,请稍后再试");if(r&&2===y.status)return null==p||p(y.result.data,y.result.loadingKey,y.result.res),Promise.resolve(y.result);if(y.output="function"==typeof m?m(y.params&&JSON.parse(JSON.stringify(y.params))):y.params&&JSON.parse(JSON.stringify(y.params)),a&&n&&1===y.status&&await y.cancelApi(),y.sendLatestKey===g&&1===y.status||(o&&g&&g in o&&(o[g]=!0),u&&u(y.params&&JSON.parse(JSON.stringify(y.params)),g)),g){const e=g;y.sendNum[e]=(y.sendNum[e]||0)+1,v[e]=y.sendNum[e]}y.sendLatestKey=g,y.status=1,y.pm=e(y.output);const l=await y.pm;y.status=2,y.result.res=l,y.result.loadingKey=g,"function"==typeof f&&(y.result.data=null==f?void 0:f(l)),null==p||p(y.result.data,g,y.result.res)}catch(O){y.status=3,y.err=O,null==d||d(y.err)}const N=y.sendLatestKey;return(y.sendLatestKey!=g||N&&v[N]===y.sendNum[N])&&(o&&g&&g in o&&(o[g]=!1),null==l||l(S)),new Promise((e,t)=>{2===y.status?e(y.result):3===y.status?t(y.err):t(new Error("useApi exception"))})},o,{...y}]},e.useData=t,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=index.umd.js.map