UNPKG

@magic_npm/simple-tools

Version:

`simple-tools` is a simple set of tools

101 lines (100 loc) 3.25 kB
const u = function(s) { const a = s(); return [ a, /* @name 合并数据,数据初始化的合并 @param coverData [object] @param isReset [boolean] // 重置性合并 @return object */ (n, m) => { let l = m || !n ? u.mergeData(s(), n) : n; return u.mergeData(a, l); } ]; }; u.getDataType = function(s) { return Object.prototype.toString.call(s).slice(8, -1).toLowerCase(); }; u.mergeData = function(s, a) { return u.getDataType(s) === "object" && ["object", "undefined"].includes(u.getDataType(a)) && a && Object.keys(s).forEach((n) => { n in a && (s[n] = a[n]); }), s; }; function D(s, a) { const { isCancel: n, isRepeat: m, isSingle: l, loading: i, params: d, loadingStart: N, loadingEnd: S, before: J, success: o, error: O, inputModel: y, outputModel: b } = { isCancel: !0, isRepeat: !0, isSingle: !1, ...a }, e = { status: 0, sendNum: {}, sendLatestKey: void 0, pm: void 0, err: "", params: void 0, output: void 0, result: { res: void 0, data: void 0, loadingKey: void 0 }, cancelApi: async () => { var f; const c = (f = e.pm) == null ? void 0 : f.cancel, t = Promise.resolve(); if (c) { c == null || c(), e.status = 0; try { await e.pm; } catch { } console.log("[cancel successful]"); } else console.log("[cancel error] find not cancel function."); return t; } }; return [async (c, t = "value") => { let f; const w = {}; try { if (e.params = d == null ? void 0 : d(), e.params && u.mergeData(e.params, c), typeof J == "function") { let r = J(e.params && JSON.parse(JSON.stringify(e.params))); if (r === !1) throw "close send api."; r instanceof Promise && await r; } if (!m && e.status === 1) return Promise.reject("操作频繁,请稍后再试"); if (l && e.status === 2) return o == null || o(e.result.data, e.result.loadingKey, e.result.res), Promise.resolve(e.result); if (e.output = typeof b == "function" ? b(e.params && JSON.parse(JSON.stringify(e.params))) : e.params && JSON.parse(JSON.stringify(e.params)), n && m && e.status === 1 && await e.cancelApi(), e.sendLatestKey === t && e.status === 1 || (i && t && t in i && (i[t] = !0), f = N == null ? void 0 : N(e.params && JSON.parse(JSON.stringify(e.params)), t)), t) { const r = t; e.sendNum[r] = (e.sendNum[r] || 0) + 1, w[r] = e.sendNum[r]; } e.sendLatestKey = t, e.status = 1, e.pm = s(e.output); const p = await e.pm; e.status = 2, e.result.res = p, e.result.loadingKey = t, e.result.data = y == null ? void 0 : y(p), o == null || o(e.result.data, t); } catch (p) { e.status = 3, e.err = p, O == null || O(e.err); } const v = e.sendLatestKey; return (e.sendLatestKey != t || w[v] === e.sendNum[v]) && (i && t && t in i && (i[t] = !1), S == null || S(f)), new Promise((p, r) => { e.status === 2 ? p(e.result) : e.status === 3 ? r(e.err) : r(new Error("useApi 异常")); }); }, i, { ...e }]; } export { D as useApi, u as useData };