UNPKG

@magic_npm/simple-tools

Version:

`simple-tools` is a simple set of tools

3 lines (2 loc) 2.38 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=function(t){const s=t();return[s,(a,r)=>{const n=r||!a?e.mergeData(t(),a):a;return e.mergeData(s,n)}]};e.getDataType=function(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()},e.mergeData=function(t,s){return t&&"object"===e.getDataType(t)&&["object","undefined"].includes(e.getDataType(s))&&s&&Object.keys(t).forEach(e=>{e in s&&(t[e]=s[e])}),t},exports.useApi=function(t,s){const{isCancel:a,isRepeat:r,isSingle:n,loading:o,params:i,loadingStart:u,loadingEnd:l,before:c,success:p,error:d,inputModel:m,outputModel:f}={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 v;const S={};try{if(y.params=null==i?void 0:i(),y.params&&e.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(!r&&1===y.status)return Promise.reject("操作频繁,请稍后再试");if(n&&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 f?f(y.params&&JSON.parse(JSON.stringify(y.params))):y.params&&JSON.parse(JSON.stringify(y.params)),a&&r&&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,S[e]=y.sendNum[e]}y.sendLatestKey=g,y.status=1,y.pm=t(y.output);const l=await y.pm;y.status=2,y.result.res=l,y.result.loadingKey=g,"function"==typeof m&&(y.result.data=null==m?void 0:m(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&&S[N]===y.sendNum[N])&&(o&&g&&g in o&&(o[g]=!1),null==l||l(v)),new Promise((e,t)=>{2===y.status?e(y.result):3===y.status?t(y.err):t(new Error("useApi exception"))})},o,{...y}]},exports.useData=e; //# sourceMappingURL=index.cjs.map