vue3-request 1.0.18 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,34 @@
1
- 一个Vue3的异步请求处理库,旨在简化你的异步操作和api调用
1
+ ## ⚡ 快速安装
2
+
3
+ ```bash [pnpm]
4
+ pnpm add vue3-request
5
+ ```
6
+
7
+ ## 🚀 5 分钟上手
8
+
9
+ ```vue
10
+ <template>
11
+ <div>
12
+ <div v-if="loading">加载中...</div>
13
+ <div v-else-if="error">{{ error.message }}</div>
14
+ <div v-else>{{ data }}</div>
15
+ <button @click="refresh">刷新</button>
16
+ <button @click="abort">中止</button>
17
+ </div>
18
+ </template>
19
+
20
+ <script setup lang="ts">
21
+ import { useRequest } from "vue3-request";
22
+
23
+ const getUserInfo = async () => {
24
+ const response = await fetch("/api/userInfo", {
25
+ signal: signal.value,
26
+ });
27
+ return response.json();
28
+ };
29
+
30
+ // 一行代码搞定状态管理
31
+ const { data, error, loading, signal, refresh, abort } =
32
+ useRequest(getUserInfo);
33
+ </script>
34
+ ```
@@ -1,509 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const l = require("vue"),
4
- C = (e) => e == null;
5
- function S(e) {
6
- return C(e) ? e : typeof e == "number" && !isNaN(e);
7
- }
8
- function w(e, t) {
9
- return S(e) === void 0
10
- ? { is: !1, value: 0 }
11
- : S(e)
12
- ? t && e === -1
13
- ? { is: !0, value: -1 }
14
- : { is: !0, value: e === 0 || (e && e < 0) ? 0 : e }
15
- : { is: !1, value: 0 };
16
- }
17
- const F = (e) => new Promise((t) => setTimeout(t, e)),
18
- E = (e, t) => {
19
- let s = t;
20
- for (let n = e.length; n-- > 0; ) {
21
- const r = e[n];
22
- s = r(s);
23
- }
24
- return s?.();
25
- },
26
- P = () => new Promise(() => {});
27
- class q {
28
- constructor(t, s) {
29
- (this.service = t),
30
- (this.options = s),
31
- (this.currentRequestId = 0),
32
- (this.pluginImpls = []),
33
- (this.setState = (n) => {
34
- Object.assign(this.state, n);
35
- }),
36
- (this.executePlugin = (n, ...r) => {
37
- if (n === "onRequest")
38
- return {
39
- servicePromise: E(
40
- this.pluginImpls.map((a) => a.onRequest).filter(Boolean),
41
- r[0]
42
- ),
43
- };
44
- {
45
- const i = this.pluginImpls
46
- .map((a) => a[n]?.apply(a, r))
47
- .filter(Boolean);
48
- return Object.assign({}, ...i);
49
- }
50
- }),
51
- (this.loading = (n) => {
52
- this.setState({ isLoading: n, isFinished: !n });
53
- }),
54
- (this.onFinished = () => {
55
- this.executePlugin(
56
- "onFinally",
57
- this.state.params,
58
- this.state.data,
59
- this.state.error
60
- ),
61
- this.loading(!1),
62
- this.options.onFinally?.(
63
- this.state.params,
64
- this.state.data,
65
- this.state.error
66
- );
67
- }),
68
- (this.runAsync = async (...n) => {
69
- const r = ++this.currentRequestId,
70
- {
71
- signal: i,
72
- isStaleTime: a,
73
- isReady: o,
74
- } = this.executePlugin("onBefore", this.state.params);
75
- if (!o) return P();
76
- if ((n.length && this.setState({ params: n }), this.loading(!0), a))
77
- return this.loading(!1), this.state.data;
78
- this.options.onBefore?.(this.state.params);
79
- try {
80
- const h = () => this.service(i)(...this.state.params);
81
- let { servicePromise: f } = this.executePlugin("onRequest", h);
82
- f || (f = h());
83
- const u = await f;
84
- return r !== this.currentRequestId
85
- ? P()
86
- : (this.setState({ data: u }),
87
- this.executePlugin("onSuccess", u, this.state.params),
88
- this.options.onSuccess?.(u, this.state.params),
89
- this.onFinished(),
90
- u);
91
- } catch (h) {
92
- if (r !== this.currentRequestId) return P();
93
- const f = h;
94
- throw (
95
- (this.setState({ error: f }),
96
- this.executePlugin("onError", f, this.state.params),
97
- this.options.onError?.(f, this.state.params),
98
- this.onFinished(),
99
- f)
100
- );
101
- }
102
- }),
103
- (this.run = (...n) => {
104
- this.runAsync(...n).catch((r) => {
105
- this.options.onError;
106
- });
107
- }),
108
- (this.refresh = () => {
109
- this.run(...this.state.params);
110
- }),
111
- (this.refreshAsync = async () =>
112
- await this.runAsync(...this.state.params)),
113
- (this.cancel = () => {
114
- (this.currentRequestId = 0),
115
- this.loading(!1),
116
- this.executePlugin("onCancel");
117
- }),
118
- (this.state = l.reactive({
119
- data: void 0,
120
- isLoading: !1,
121
- isFinished: !1,
122
- isAborted: !1,
123
- error: void 0,
124
- params: s?.defaultParams || [],
125
- }));
126
- }
127
- }
128
- const R = new Map(),
129
- x = (e, { data: t, params: s, time: n }) => {
130
- R.set(e, { data: t, params: s, time: n });
131
- },
132
- y = (e) => R.get(e),
133
- A = (e) => {
134
- e ? R.delete(e) : R.clear();
135
- };
136
- function O(e, t, s) {
137
- const n = { manual: !1, defaultParams: [], ...t },
138
- r = new q(e, n);
139
- (r.pluginImpls = s.map((c) => c(r, n))),
140
- n.manual || r.run(...n.defaultParams),
141
- l.onUnmounted(r.cancel);
142
- const {
143
- run: i,
144
- cancel: a,
145
- refresh: o,
146
- runAsync: h,
147
- refreshAsync: f,
148
- abort: u,
149
- } = r;
150
- return {
151
- ...l.toRefs(r.state),
152
- run: i,
153
- cancel: a,
154
- refresh: o,
155
- runAsync: h,
156
- abort: u,
157
- refreshAsync: f,
158
- clearCache: A,
159
- };
160
- }
161
- const B = (e) => {
162
- let t = null,
163
- { setState: s } = e;
164
- const n = () => (
165
- (t = new AbortController()),
166
- s({ isAborted: t.signal.aborted }),
167
- { signal: t.signal }
168
- );
169
- return (
170
- (e.abort = () => {
171
- t &&
172
- !t.signal.aborted &&
173
- !e.state.isFinished &&
174
- (t.abort(), s({ isAborted: t.signal.aborted }));
175
- }),
176
- {
177
- onBefore: () => {
178
- e.abort();
179
- const { signal: r } = n();
180
- return { signal: r };
181
- },
182
- onRequest: (r) => r,
183
- onCancel: () => {
184
- e.abort(), (t = null);
185
- },
186
- }
187
- );
188
- },
189
- v = new Map(),
190
- I = (e, { data: t, params: s, time: n }) => {
191
- v.has(e) && v.get(e)?.forEach((i) => i({ data: t, params: s, time: n }));
192
- },
193
- T = (e, t) => (
194
- v.has(e) ? v.get(e)?.add(t) : v.set(e, new Set()),
195
- () => {
196
- const s = v.get(e);
197
- s?.delete(t), s?.size === 0 && v.delete(e);
198
- }
199
- ),
200
- b = new Map(),
201
- L = (e, t) => {
202
- b.set(e, t),
203
- t
204
- .then(() => {})
205
- .catch(() => {})
206
- .finally(() => {
207
- W(e);
208
- });
209
- },
210
- M = (e) => b.get(e),
211
- W = (e) => {
212
- e ? b.delete(e) : b.clear();
213
- },
214
- j = (
215
- e,
216
- { cacheKey: t, cacheTime: s = new Date(0).setMinutes(5), staleTime: n = 0 }
217
- ) => {
218
- const { setState: r } = e,
219
- i = l.ref(null);
220
- let a = null;
221
- const o = (u) => {
222
- t &&
223
- (a && (window.clearTimeout(a), (a = null)),
224
- (a = window.setTimeout(() => {
225
- A(t), (a = null);
226
- }, u)));
227
- };
228
- function h() {
229
- if (!t) return;
230
- const u = y(t);
231
- u && r({ data: u.data, params: u.params }),
232
- (i.value = T(t, (c) => {
233
- r({ data: c.data, params: c.params });
234
- }));
235
- }
236
- h();
237
- const f = () => {
238
- if (!t) return null;
239
- const u = y(t);
240
- return !u || Date.now() - u.time > n ? null : !0;
241
- };
242
- return {
243
- onBefore: () => (f() ? { isStaleTime: !0 } : { isStaleTime: !1 }),
244
- onRequest: (u) => {
245
- if (!t) return u;
246
- let c = M(t);
247
- return c ? () => c : ((c = u()), L(t, c), () => c);
248
- },
249
- onSuccess: (u, c) => {
250
- if (!t) return;
251
- const d = { data: u, params: c, time: Date.now() };
252
- i.value?.(),
253
- (i.value = T(t, (m) => {
254
- r({ data: m.data, params: m.params });
255
- })),
256
- x(t, d),
257
- I(t, d),
258
- o(s);
259
- },
260
- onCancel: () => {
261
- i.value?.();
262
- },
263
- };
264
- },
265
- D = (e, { errorRetryCount: t = 0, errorRetryInterval: s }) => {
266
- const n = l.ref(0),
267
- r = l.ref(!0),
268
- { refresh: i } = e,
269
- a = l.computed(() => 1e3 * Math.pow(2, n.value)),
270
- o = () => {
271
- (n.value = 0), (r.value = !1);
272
- },
273
- h = async () => {
274
- let { is: u, value: c } = w(l.toValue(s));
275
- u || (c = l.toValue(a)), await F(c), i();
276
- },
277
- f = async () => {
278
- const { is: u, value: c } = w(l.toValue(t), !0);
279
- u && (n.value++, c === -1 || n.value <= c ? await h() : (n.value = 0));
280
- };
281
- return {
282
- onError: () => {
283
- r.value ? f() : (r.value = !0);
284
- },
285
- onCancel: () => {
286
- o();
287
- },
288
- };
289
- },
290
- N = (e, { pollingInterval: t }) => {
291
- const { refresh: s } = e;
292
- let n = null;
293
- const r = () => {
294
- const { is: a, value: o } = w(l.toValue(t));
295
- a && (i(), (n = window.setInterval(s, o)));
296
- },
297
- i = () => {
298
- n && window.clearInterval(n), (n = null);
299
- };
300
- return {
301
- onBefore: () => {
302
- r();
303
- },
304
- onCancel: () => {
305
- i();
306
- },
307
- };
308
- },
309
- V = (e, { refreshDeps: t = [], refreshDepsAction: s }) => {
310
- const { refresh: n } = e,
311
- r = l.watch(
312
- t,
313
- () => {
314
- if (s) return s();
315
- n();
316
- },
317
- { deep: !0 }
318
- );
319
- return {
320
- onCancel: () => {
321
- r();
322
- },
323
- };
324
- },
325
- z = (e, { refocusTimespan: t = 5e3, refreshOnWindowFocus: s }) => {
326
- const { refresh: n } = e,
327
- r = l.ref(!0);
328
- function i() {
329
- s &&
330
- (window.addEventListener("focus", a),
331
- window.document.addEventListener("visibilitychange", a));
332
- }
333
- i();
334
- async function a() {
335
- const { is: o, value: h } = w(t);
336
- o &&
337
- window.document.visibilityState === "visible" &&
338
- navigator.onLine &&
339
- r.value &&
340
- (n(), (r.value = !1), await F(h), (r.value = !0));
341
- }
342
- return {
343
- onCancel: () => {
344
- window.removeEventListener("focus", a),
345
- window.document.removeEventListener("visibilitychange", a);
346
- },
347
- };
348
- },
349
- U = (e, { manual: t, ready: s = l.ref(!0) }) => {
350
- const n = l.computed(() => l.toValue(s)),
351
- r = l.watch(n, (i) => {
352
- !t && i && e.refresh();
353
- });
354
- return {
355
- onBefore: () => {
356
- if (n.value) return { isReady: !0 };
357
- },
358
- onCancel: () => {
359
- r();
360
- },
361
- };
362
- };
363
- function G(e, t, s) {
364
- var n = null,
365
- r = null,
366
- i =
367
- typeof s == "boolean"
368
- ? { leading: s, trailing: !s }
369
- : Object.assign({ leading: !1, trailing: !0 }, s),
370
- a = !1,
371
- o = null,
372
- h = i.leading,
373
- f = i.trailing,
374
- u = function () {
375
- (n = null), (r = null);
376
- },
377
- c = function () {
378
- (a = !0), e.apply(r, n), u();
379
- },
380
- d = function () {
381
- if ((h === !0 && (o = null), a)) {
382
- u();
383
- return;
384
- }
385
- if (f === !0) {
386
- c();
387
- return;
388
- }
389
- u();
390
- },
391
- m = function () {
392
- var p = o !== null;
393
- return p && clearTimeout(o), u(), (o = null), (a = !1), p;
394
- },
395
- g = function () {
396
- (a = !1),
397
- (n = arguments),
398
- (r = this),
399
- o === null ? h === !0 && c() : clearTimeout(o),
400
- (o = setTimeout(d, t));
401
- };
402
- return (g.cancel = m), g;
403
- }
404
- const H = (e, { debounceWait: t, debounceOptions: s, manual: n }) => {
405
- let r = n,
406
- i = null;
407
- const a = l.computed(() => l.toValue(t)),
408
- o = l.computed(() => l.toValue(s)),
409
- h = e.runAsync;
410
- return (
411
- r || (r = !0),
412
- l.watchEffect(() => {
413
- C(a.value) ||
414
- ((i = G((f) => f(), a.value, o.value)),
415
- (e.runAsync = (...f) =>
416
- new Promise((u, c) => {
417
- r
418
- ? ((r = !1),
419
- h(...f)
420
- .then(u)
421
- .catch(c))
422
- : i(() => {
423
- h(...f)
424
- .then(u)
425
- .catch(c);
426
- });
427
- })),
428
- l.onWatcherCleanup(() => {
429
- i?.cancel(), (e.runAsync = h);
430
- }));
431
- }),
432
- {
433
- onCancel: () => {
434
- i?.cancel(), (i = null), (r = !1);
435
- },
436
- }
437
- );
438
- };
439
- function J(e, t, s) {
440
- var n = null,
441
- r = null,
442
- i = !1,
443
- a = null,
444
- o = Object.assign({ leading: !0, trailing: !0 }, s),
445
- h = o.leading,
446
- f = o.trailing,
447
- u = function () {
448
- (n = null), (r = null);
449
- },
450
- c = function () {
451
- (i = !0), e.apply(r, n), (a = setTimeout(d, t)), u();
452
- },
453
- d = function () {
454
- if (((a = null), i)) {
455
- u();
456
- return;
457
- }
458
- if (f === !0) {
459
- c();
460
- return;
461
- }
462
- u();
463
- },
464
- m = function () {
465
- var p = a !== null;
466
- return p && clearTimeout(a), u(), (a = null), (i = !1), p;
467
- },
468
- g = function () {
469
- if (((n = arguments), (r = this), (i = !1), a === null && h === !0)) {
470
- c();
471
- return;
472
- }
473
- f === !0 && (a = setTimeout(d, t));
474
- };
475
- return (g.cancel = m), g;
476
- }
477
- const Q = (e, { throttleWait: t, throttleOptions: s }) => {
478
- let n = null;
479
- const r = l.computed(() => l.toValue(t)),
480
- i = l.computed(() => l.toValue(s)),
481
- a = e.runAsync;
482
- return (
483
- l.watchEffect(() => {
484
- C(r.value) ||
485
- ((n = J((o) => o(), r.value, i.value)),
486
- (e.runAsync = (...o) =>
487
- new Promise((h, f) => {
488
- n(() => {
489
- a(...o)
490
- .then(h)
491
- .catch(f);
492
- });
493
- })),
494
- l.onWatcherCleanup(() => {
495
- n?.cancel(), (e.runAsync = a);
496
- }));
497
- }),
498
- {
499
- onCancel: () => {
500
- n?.cancel(), (n = null);
501
- },
502
- }
503
- );
504
- },
505
- X = [D, N, V, z, B, U, H, Q, j];
506
- function Y(e, t, s) {
507
- return O(e, t, [...(s || []), ...X]);
508
- }
509
- exports.useRequest = Y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("vue"),b=e=>e,V=e=>e==null;function A(e){return V(e)?e:typeof e=="number"&&!isNaN(e)}function w(e,t){return A(e)===void 0?{is:!1,value:0}:A(e)?t&&e===-1?{is:!0,value:-1}:{is:!0,value:e===0||e&&e<0?0:e}:{is:!1,value:0}}const M=(e,t)=>{let n=t;for(let s=e.length;s-- >0;){const r=e[s];n=r(n)}return n?.()},C=()=>new Promise(()=>{}),O=e=>e instanceof Function,R=new Map,L=(e,t,{data:n,params:s,time:r})=>{let u;const a=x(e),{is:o,value:l}=w(t,!0);o&&(a?.timer&&window.clearTimeout(a?.timer),l!==-1&&(u=window.setTimeout(()=>{T(e)},l)),R.set(e,{data:n,params:s,time:r,timer:u}))},x=e=>R.get(e),T=e=>{e&&typeof e=="string"?R.delete(e):R.clear()};class j{constructor(t,n){this.service=t,this.options=n,this.state=i.reactive({data:void 0,error:void 0,params:n?.defaultParams||[],loading:!1,isFinished:!1,isAborted:!1,signal:new AbortController().signal})}currentRequestId=0;pluginImpls=[];state;abort=()=>{};setState=t=>{Object.assign(this.state,t)};executePlugin=(t,...n)=>{if(t==="onRequest")return{servicePromise:M(this.pluginImpls.map(r=>r.onRequest).filter(Boolean),n[0])};{const s=this.pluginImpls.map(r=>r[t]?.(...n)).filter(Boolean);return Object.assign({},...s)}};loading=t=>{this.setState({loading:t,isFinished:!t})};onFinished=()=>{this.executePlugin("onFinally",this.state.params,this.state.data,this.state.error),this.loading(!1),this.options.onFinally?.(this.state.params,this.state.data,this.state.error)};runAsync=async(...t)=>{const n=++this.currentRequestId,{isReturn:s,isReady:r,...u}=this.executePlugin("onBefore",t);if(!r)return C();if(this.setState({params:t}),this.loading(!0),s)return this.loading(u.loading||!1),u.data;this.options.onBefore?.(t);try{const a=()=>this.service(...t);let{servicePromise:o}=this.executePlugin("onRequest",a);o||(o=a());const l=await o;return n!==this.currentRequestId?C():(this.setState({data:l,error:void 0}),this.executePlugin("onSuccess",l,t),this.options.onSuccess?.(l,t),this.onFinished(),l)}catch(a){if(n!==this.currentRequestId)return C();const o=a;throw this.setState({data:void 0,error:o}),this.executePlugin("onError",o,t),this.options.onError?.(o,t),this.onFinished(),o}};run=(...t)=>{this.runAsync(...t).catch(n=>{this.options.onError})};refresh=()=>{this.run(...this.state.params)};refreshAsync=async()=>await this.runAsync(...this.state.params);mutate=t=>{O(t)?t(this.state.data):this.setState({data:t}),this.executePlugin("onMutate",this.state.data)};cancel=()=>{this.executePlugin("onCancel"),this.currentRequestId++,this.loading(!1)}}function N(e,t,n){const s={manual:!1,...t},r=new j(e,s);r.pluginImpls=n.map(g=>g(r,s)),i.onMounted(()=>{if(!s.manual){const g=r.state.params;r.run(...g)}}),i.onUnmounted(r.cancel);const{run:u,cancel:a,refresh:o,runAsync:l,refreshAsync:v,abort:f,mutate:h}=r;return{...i.toRefs(r.state),run:u,cancel:a,refresh:o,runAsync:l,mutate:h,abort:f,refreshAsync:v,clearCache:T}}const U=b((e,{abortPrevious:t=!0})=>{let n=null;const s=()=>{n=new AbortController,e.setState({signal:n.signal,isAborted:n.signal.aborted})};return e.abort=()=>{n&&!n.signal.aborted&&!e.state.isFinished&&(n.abort(),e.setState({isAborted:n.signal.aborted}))},{onBefore:()=>{typeof t=="boolean"&&t&&e.abort(),s()},onRequest:r=>()=>r(),onCancel:()=>{e.abort(),n=null}}}),p=new Map,D=(e,{data:t,params:n,time:s})=>{p.has(e)&&p.get(e)?.forEach(u=>u({data:t,params:n,time:s}))},E=(e,t)=>(p.has(e)?p.get(e)?.add(t):p.set(e,new Set),()=>{const n=p.get(e);n?.delete(t),n?.size===0&&p.delete(e)}),P=new Map,W=(e,t)=>{P.set(e,t),t.then(n=>{}).catch(()=>{}).finally(()=>{_(e)})},H=e=>P.get(e),_=e=>{e&&typeof e=="string"?P.delete(e):P.clear()},$=b((e,{cacheKey:t,cacheTime:n=3e5,staleTime:s=0,setCache:r,getCache:u})=>{const a=i.ref(null);let o=null;const{is:l,value:v}=w(s,!0);if(!l)return{};const f=(c,d)=>{r?r(c,d):L(c,n,d),D(c,d)},h=c=>u?u(c):x(c);function g(){if(!t)return;const c=h(t);c&&Reflect.has(c,"data")&&e.setState({data:c.data,params:c.params}),a.value=E(t,d=>{e.setState({data:d.data})})}return g(),i.onUnmounted(()=>{a.value?.()}),{onBefore:()=>{if(!t)return null;const c=h(t);return!c||!Reflect.has(c,"data")?{}:v===-1||Date.now()-c.time<v?{loading:!1,data:c.data,error:void 0,isReturn:!0}:{data:c.data,error:void 0}},onRequest:c=>{if(!t)return c;let d=H(t);return d&&d!==o?()=>d:(d=c(),o=d,W(t,d),()=>d)},onSuccess:(c,d)=>{if(!t)return;const m={data:c,params:d,time:Date.now()};a.value?.(),f(t,m),a.value=E(t,B=>{e.setState({data:B.data})})}}}),z=b((e,{errorRetryCount:t=0,errorRetryInterval:n})=>{const s=i.ref(),r=i.ref(0),u=i.ref(!1),a=i.computed(()=>1e3*Math.pow(2,r.value)),o=()=>{let f=null;r.value++;const{value:h}=w(i.toValue(t),!0),g=h===-1,c=r.value<=h;if(g||c){let{is:d,value:m}=w(i.toValue(n));d||(m=i.toValue(Math.min(a.value,3e4))),f=window.setTimeout(()=>{u.value=!0,e.refresh()},m)}return()=>{f&&window.clearTimeout(f)}},l=()=>{s.value?.()},{is:v}=w(i.toValue(t),!0);return v?{onBefore:()=>{u.value||(r.value=0),u.value=!1,l()},onSuccess:()=>{r.value=0},onError:()=>{s.value=o()},onCancel:()=>{r.value=0,l()}}:{}}),y=()=>document.visibilityState==="visible",F=new Set,I=e=>(F.add(e),()=>{F.delete(e)}),J=()=>{y()&&F.forEach(e=>{e()})};window.addEventListener("visibilitychange",J,!1);const Q=b((e,{pollingInterval:t,pollingWhenHidden:n=!0,errorRetryCount:s})=>{const r=i.ref(null),u=i.ref(),a=()=>{let o;const{value:l}=w(i.toValue(s),!0);if(e.state.error&&l!==0)return;const{is:v,value:f}=w(i.toValue(t));if(!v)return;const h=f;return o=window.setTimeout(()=>{!i.toValue(n)&&!y()?r.value=I(e.refresh):e.refresh()},h),()=>{o&&window.clearTimeout(o),r.value?.()}};return i.watch([()=>i.toValue(t),()=>i.toValue(n)],()=>{u.value?.(),u.value=a()}),i.onUnmounted(()=>{r.value?.()}),{onBefore:()=>{u.value?.()},onCancel:()=>{u.value?.()},onFinally:()=>{u.value=a()}}}),X=b((e,{manual:t,refreshDeps:n,refreshDepsAction:s})=>{if(V(n)||typeof n!="object"&&typeof n!="function")return{};const r=i.watch(n,()=>{t||(s?s():e.refresh())},{deep:!0});return{onCancel:()=>{r()}}}),Y=()=>window.navigator.onLine,S=new Set,Z=e=>(S.add(e),()=>{S.delete(e)}),q=()=>{!y()||!Y()||S.forEach(e=>{e()})};window.addEventListener("visibilitychange",q,!1);window.addEventListener("focus",q,!1);const G=b((e,{refocusTimespan:t=5e3,refreshOnWindowFocus:n=!1})=>{const s=i.ref(),{is:r}=w(i.toValue(t));if(!r||V(i.toValue(n))||typeof i.toValue(n)!="boolean")return{};const u=(a,o)=>{let l=!1;return()=>{l||(l=!0,a(),window.setTimeout(()=>{l=!1},o))}};return i.watchEffect(()=>{s.value?.(),i.toValue(n)&&(s.value=Z(u(e.refresh,i.toValue(t))))}),i.onUnmounted(()=>{s.value?.()}),{}}),k=b((e,{manual:t,ready:n=!0,defaultParams:s=[]})=>{const r=i.watch(()=>i.toValue(n),u=>{!t&&u&&e.run(...s)},{flush:"sync"});return{onBefore:()=>({isReady:i.toValue(n)}),onCancel:()=>{r()}}});function K(e,t,n){var s=null,r=null,u=typeof n=="boolean"?{leading:n,trailing:!n}:Object.assign({leading:!1,trailing:!0},n),a=!1,o=null,l=u.leading,v=u.trailing,f=function(){s=null,r=null},h=function(){a=!0,e.apply(r,s),f()},g=function(){if(l===!0&&(o=null),a){f();return}if(v===!0){h();return}f()},c=function(){var m=o!==null;return m&&clearTimeout(o),f(),o=null,a=!1,m},d=function(){a=!1,s=arguments,r=this,o===null?l===!0&&h():clearTimeout(o),o=setTimeout(g,t)};return d.cancel=c,d}const ee=b((e,{debounceWait:t,debounceOptions:n,manual:s})=>{const r=i.ref(!1);let u=null;const a=e.runAsync;return s||(r.value=!0),i.watchEffect(()=>{const{is:o,value:l}=w(i.toValue(t));if(!o)return;const v=i.toValue(n);u=K(f=>f(),l,v),e.runAsync=(...f)=>new Promise((h,g)=>{r.value?(r.value=!1,a(...f).then(h).catch(g)):u(()=>{a(...f).then(h).catch(g)})}),i.onWatcherCleanup(()=>{u?.cancel(),e.runAsync=a})}),{onCancel:()=>{u?.cancel()}}});function te(e,t,n){var s=null,r=null,u=!1,a=null,o=Object.assign({leading:!0,trailing:!0},n),l=o.leading,v=o.trailing,f=function(){s=null,r=null},h=function(){u=!0,e.apply(r,s),a=setTimeout(g,t),f()},g=function(){if(a=null,u){f();return}if(v===!0){h();return}f()},c=function(){var m=a!==null;return m&&clearTimeout(a),f(),a=null,u=!1,m},d=function(){if(s=arguments,r=this,u=!1,a===null&&l===!0){h();return}v===!0&&(a=setTimeout(g,t))};return d.cancel=c,d}const ne=b((e,{throttleWait:t,throttleOptions:n})=>{let s=null;const r=e.runAsync;return i.watchEffect(()=>{const{is:u,value:a}=w(i.toValue(t));if(!u)return;const o=i.toValue(n);s=te(l=>l(),a,o),e.runAsync=(...l)=>new Promise((v,f)=>{s(()=>{r(...l).then(v).catch(f)})}),i.onWatcherCleanup(()=>{s?.cancel(),e.runAsync=r})}),{onCancel:()=>{s?.cancel()}}}),re=[z,Q,X,G,U,k,ee,ne,$];function se(e,t,n){return N(e,t||{},[...n||[],...re])}exports.clearCache=T;exports.definePlugin=b;exports.useRequest=se;
@@ -1,55 +1,73 @@
1
1
  import { Reactive } from 'vue';
2
2
  import { Ref } from 'vue';
3
3
  import { ToRefs } from 'vue';
4
+ import { WatchSource } from 'vue';
4
5
 
5
- declare type CallbackType<D = any, P extends any[] = any> = (signal?: AbortSignal) => ServiceType<D, P>;
6
-
7
- declare type DebounceOptionsType = {
8
- leading?: boolean;
9
- trailing?: boolean;
10
- };
11
-
12
- declare type IOptions<D, P extends any[]> = Partial<{
6
+ declare type BaseOptions<D, P extends any[]> = Partial<{
13
7
  onBefore: (params: P) => void;
14
8
  onSuccess: (data: D, params: P) => void;
15
- onFinally: (params: P, data: D, error: Error) => void;
9
+ onFinally: (params: P, data?: D, error?: Error) => void;
16
10
  onError: (error: Error, params: P) => void;
17
11
  manual: boolean;
18
12
  defaultParams: P;
19
- refreshDeps: (Ref<any> | Reactive<any>)[];
13
+ refreshDeps: WatchSource | WatchSource[] | object;
20
14
  refreshDepsAction: () => void;
21
15
  pollingInterval: number | Ref<number>;
16
+ pollingWhenHidden: boolean | Ref<boolean>;
22
17
  errorRetryCount: number | Ref<number>;
23
18
  errorRetryInterval: number | Ref<number>;
24
- refreshOnWindowFocus: boolean;
25
- refocusTimespan: number;
19
+ refreshOnWindowFocus: boolean | Ref<boolean>;
20
+ refocusTimespan: number | Ref<number>;
26
21
  cacheKey: string;
27
22
  cacheTime: number;
28
23
  staleTime: number;
24
+ setCache: (cacheKey: string, cacheData: CacheParamsType) => void;
25
+ getCache: (cacheKey: string) => CacheParamsType;
29
26
  ready: Ref<boolean> | (() => boolean);
30
27
  debounceWait: Ref<number> | number;
31
28
  debounceOptions: Reactive<DebounceOptionsType> | DebounceOptionsType;
32
29
  throttleWait: Ref<number> | number;
33
30
  throttleOptions: Reactive<ThrottleOptionsType> | ThrottleOptionsType;
31
+ abortPrevious: boolean;
34
32
  }>;
35
33
 
34
+ declare type CacheParamsType<D = any, P = any> = {
35
+ data?: D;
36
+ params: P;
37
+ time: number;
38
+ } & {
39
+ timer?: number;
40
+ };
41
+
42
+ export declare const clearCache: (cacheKey?: string) => void;
43
+
44
+ declare type DebounceOptionsType = {
45
+ leading?: boolean;
46
+ trailing?: boolean;
47
+ };
48
+
49
+ export declare const definePlugin: <D = any, P extends any[] = any, O = {}>(plugin: Plugin_2<D, P, O>) => Plugin_2<D, P, O>;
50
+
36
51
  declare interface IState<D, P extends any[]> {
37
- data: D | undefined;
38
- isLoading: boolean;
52
+ data?: D;
53
+ loading: boolean;
39
54
  isFinished: boolean;
40
55
  isAborted: boolean;
41
- error: Error | undefined;
56
+ error?: Error;
42
57
  params: P;
58
+ signal: AbortSignal;
43
59
  }
44
60
 
45
- declare type Plugin_2<D = any, P extends any[] = any> = (requestInstance: Request_2<D, P>, options: IOptions<D, P>) => PluginReturn<D, P>;
61
+ declare type Plugin_2<D = any, P extends any[] = any, O = {}> = (requestInstance: Request_2<D, P>, options: BaseOptions<D, P> & O) => PluginReturn<D, P>;
46
62
  export { Plugin_2 as Plugin }
47
63
 
48
64
  declare type PluginMethodsReturn<D, P extends any[]> = Partial<{
49
- servicePromise?: ReturnType<ServiceType<D, P>>;
50
- signal?: AbortSignal;
51
- isStaleTime?: boolean;
52
- isReady?: boolean;
65
+ servicePromise: ReturnType<ServiceType<D, P>>;
66
+ signal: AbortSignal;
67
+ isReturn: boolean;
68
+ isReady: boolean;
69
+ data?: D;
70
+ loading: boolean;
53
71
  }>;
54
72
 
55
73
  declare type PluginReturn<D, P extends any[]> = Partial<{
@@ -58,25 +76,27 @@ declare type PluginReturn<D, P extends any[]> = Partial<{
58
76
  onFinally: (params: P, data: D, error: Error) => void;
59
77
  onError: (error: Error, params: P) => void;
60
78
  onCancel: () => void;
79
+ onMutate: (data: D | ((data: D) => D)) => void;
61
80
  onRequest: (service: ServiceType<D, P>) => ServiceType<D, P>;
62
81
  }>;
63
82
 
64
83
  declare class Request_2<D, P extends any[]> {
65
- service: CallbackType<D, P>;
66
- options?: IOptions<D, P>;
84
+ service: ServiceType<D, P>;
85
+ options: BaseOptions<D, P>;
67
86
  currentRequestId: number;
68
87
  pluginImpls: PluginReturn<D, P>[];
69
88
  state: IState<D, P>;
70
89
  abort: () => void;
71
- constructor(service: CallbackType<D, P>, options?: IOptions<D, P>);
90
+ constructor(service: ServiceType<D, P>, options: BaseOptions<D, P>);
72
91
  setState: (s: Partial<IState<D, P>>) => void;
73
92
  executePlugin: (event: keyof PluginReturn<D, P>, ...rest: any[]) => PluginMethodsReturn<D, P>;
74
- loading: (isLoading: boolean) => void;
93
+ loading: (loading: boolean) => void;
75
94
  onFinished: () => void;
76
95
  runAsync: (...params: P) => Promise<D>;
77
96
  run: (...params: P) => void;
78
97
  refresh: () => void;
79
98
  refreshAsync: () => Promise<D>;
99
+ mutate: (data: D | ((data: D) => D)) => void;
80
100
  cancel: () => void;
81
101
  }
82
102
 
@@ -87,7 +107,9 @@ declare type ThrottleOptionsType = {
87
107
  trailing?: boolean;
88
108
  };
89
109
 
90
- export declare function useRequest<D, P extends any[]>(service: CallbackType<D, P>, options?: IOptions<D, P>, plugins?: Plugin_2<D, P>[]): UseRequestReturnType<D, P>;
110
+ export declare function useRequest<D, P extends any[] = any[]>(service: ServiceType<D, P>, options?: BaseOptions<D, P>): UseRequestReturnType<D, P>;
111
+
112
+ export declare function useRequest<D, P extends any[] = any[], O = {}>(service: ServiceType<D, P>, options: BaseOptions<D, P> & O, plugins: Plugin_2<D, P, O>[]): UseRequestReturnType<D, P>;
91
113
 
92
114
  declare interface UseRequestReturnType<D, P extends any[]> extends ToRefs<IState<D, P>> {
93
115
  run: (...args: P) => void;
@@ -96,7 +118,8 @@ declare interface UseRequestReturnType<D, P extends any[]> extends ToRefs<IState
96
118
  runAsync: (...args: P) => Promise<D>;
97
119
  abort: () => void;
98
120
  refreshAsync: () => Promise<D>;
99
- clearCache: () => void;
121
+ clearCache: (key?: string) => void;
122
+ mutate: (data: D | ((data: D) => D)) => void;
100
123
  }
101
124
 
102
125
  export { }