Skip to content

Commit 7aab755

Browse files
committed
feat: use-request image v1.2.0
1 parent 95bdbd6 commit 7aab755

File tree

7 files changed

+109
-50
lines changed

7 files changed

+109
-50
lines changed

packages/use-request/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@vue-hooks-plus/use-request",
3-
"version": "1.1.0",
3+
"version": "1.2.0",
44
"description": "Vue use-request hooks library",
55
"files": [
66
"dist",

packages/use-request/src/Fetch.ts

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
2121
constructor(
2222
public serviceRef: Ref<UseRequestService<TData, TParams>>,
2323
public options: UseRequestOptions<TData, TParams, any>,
24-
public setUpdateData: (s: any, key?: keyof UseRequestFetchState<TData, TParams>) => void,
24+
public setUpdateData: (
25+
currentState: unknown,
26+
key?: keyof UseRequestFetchState<TData, TParams>,
27+
) => void,
2528
public initState: Partial<UseRequestFetchState<TData, TParams>> = {},
2629
) {
2730
this.state = {
@@ -32,38 +35,61 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
3235
}
3336

3437
// 设置state
35-
setState(s: Partial<UseRequestFetchState<TData, TParams>> = {}) {
38+
setState(currentState: Partial<UseRequestFetchState<TData, TParams>> = {}) {
3639
this.state = {
3740
...this.state,
38-
...s,
41+
...currentState,
3942
}
4043
this.setUpdateData(this.state)
4144
}
4245

4346
/**
44-
*
45-
* @param data Result value `any`
47+
* should rename
48+
* @param data Result value `unknown`
4649
* @param key Result key `data`| `params` | `loading`| `error`
4750
*/
4851
setData(
49-
data: any,
52+
data: unknown,
53+
key?:
54+
| keyof UseRequestFetchState<TData, TParams>
55+
| (keyof UseRequestFetchState<TData, TParams>)[],
56+
) {
57+
console.warn("Please use 'setFetchState' instead of 'setData'")
58+
if (key instanceof Array) {
59+
key.forEach(k => {
60+
this.state[k as keyof UseRequestFetchState<TData, TParams>] = data as any
61+
this.setUpdateData(data, k)
62+
})
63+
} else {
64+
this.state[key as keyof UseRequestFetchState<TData, TParams>] = data as any
65+
this.setUpdateData(data, key)
66+
}
67+
}
68+
69+
/**
70+
*
71+
* @param data Result value `unknown`
72+
* @param key Result key `data`| `params` | `loading`| `error`
73+
*/
74+
setFetchState(
75+
data: unknown,
5076
key?:
5177
| keyof UseRequestFetchState<TData, TParams>
5278
| (keyof UseRequestFetchState<TData, TParams>)[],
5379
) {
5480
if (key instanceof Array) {
5581
key.forEach(k => {
56-
this.state[k as keyof UseRequestFetchState<TData, TParams>] = data
82+
this.state[k as keyof UseRequestFetchState<TData, TParams>] = data as any
5783
this.setUpdateData(data, k)
5884
})
5985
} else {
60-
this.state[key as keyof UseRequestFetchState<TData, TParams>] = data
86+
this.state[key as keyof UseRequestFetchState<TData, TParams>] = data as any
6187
this.setUpdateData(data, key)
6288
}
6389
}
6490

6591
// 遍历需要运行的插件,是一个回调函数,供插件获取fetch实例和在对应节点执行插件逻辑
66-
runPluginHandler(event: keyof UseRequestPluginReturn<TData, TParams>, ...rest: any[]) {
92+
runPluginHandler(event: keyof UseRequestPluginReturn<TData, TParams>, ...rest: unknown[]) {
6793
// @ts-ignore
6894
const r = (this.pluginImpls?.map(i => i[event]?.(...rest)) ?? [])?.filter(Boolean)
6995
// @ts-ignore
@@ -102,7 +128,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
102128
// replace service 开始请求,如果含有onRequest事件名
103129
let { servicePromise } = this.runPluginHandler('onRequest', this.serviceRef.value, params)
104130

105-
const requestReturn = (res: any) => {
131+
const requestReturnResponse = (res: any) => {
106132
// 取消了请求,count将与currentCount不一致,将发送空请求
107133
if (currentCount !== this.count) {
108134
return new Promise(() => {})
@@ -135,18 +161,18 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
135161
if (!this.options.manual && this.options.refreshDeps === true) {
136162
watchEffect(async () => {
137163
if (unref(this.options.ready)) {
138-
this.setData(true, 'loading')
164+
this.setFetchState(true, 'loading')
139165
servicePromise = this.serviceRef.value(...params)
140-
const res = await servicePromise
141-
return requestReturn(res)
166+
const servicePromiseResult = await servicePromise
167+
return requestReturnResponse(servicePromiseResult)
142168
}
143169
})
144170
} else {
145171
servicePromise = this.serviceRef.value(...params)
146172
}
147173
}
148-
const res = await servicePromise
149-
return requestReturn(res)
174+
const servicePromiseResult = await servicePromise
175+
return requestReturnResponse(servicePromiseResult)
150176
} catch (error) {
151177
if (currentCount !== this.count) {
152178
return new Promise(() => {})

packages/use-request/src/plugins/useDebouncePlugin.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const useDebouncePlugin: UseRequestPlugin<unknown, unknown[]> = (
2929
if (unref(debounceWait)) {
3030
const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
3131
debouncedRef.value = debounce(
32-
(callback: any) => {
32+
(callback: () => void) => {
3333
callback();
3434
},
3535
unref(debounceWait),

packages/use-request/src/plugins/useThrottlePlugin.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const useThrottlePlugin: UseRequestPlugin<unknown, unknown[]> = (
2020

2121
const throttledRef = computed<DebouncedFunc<any>>(() =>
2222
throttle(
23-
(callback: any) => {
23+
(callback: () => void) => {
2424
callback()
2525
},
2626
unref(throttleWait),

packages/use-request/src/useRequestImplement.ts

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
1-
import { ref, reactive, toRefs, onMounted, onUnmounted, unref, inject } from 'vue'
1+
import { ref, reactive, toRefs, onMounted, onUnmounted, unref, inject, UnwrapRef } from 'vue'
22

33
import Fetch from './Fetch'
44
import { USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY } from './config'
5-
import { UseRequestOptions, UseRequestPlugin, useRequestResult, UseRequestService } from './types'
5+
import {
6+
UseRequestFetchState,
7+
UseRequestOptions,
8+
UseRequestPlugin,
9+
useRequestResult,
10+
UseRequestService,
11+
} from './types'
12+
13+
function isUseRequestFetchState<TData, TParams extends any[]>(
14+
state: unknown,
15+
): state is UseRequestFetchState<TData, TParams> {
16+
const keys = Object.keys(state as object)
17+
return keys.filter(i => ['data', 'loading', 'params', 'error'].includes(i)).length === 4
18+
}
19+
20+
// function isUseRequestFetchStateKey<TData, TParams extends any[]>(
21+
// field: string,
22+
// state: unknown,
23+
// ): state is UseRequestFetchState<TData, TParams>[keyof UseRequestFetchState<TData, TParams>] {
24+
// return Boolean(['data', 'loading', 'params', 'error'].find(i => i === field))
25+
// }
626

727
function useRequestImplement<TData, TParams extends any[]>(
828
service: UseRequestService<TData, TParams>,
@@ -12,12 +32,13 @@ function useRequestImplement<TData, TParams extends any[]>(
1232
// global option
1333
const USEREQUEST_GLOBAL_OPTIONS = inject<Record<string, any>>(
1434
USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY,
35+
{},
1536
)
1637
// read option
1738
const { initialData = undefined, manual = false, ready = true, ...rest } = {
1839
...(USEREQUEST_GLOBAL_OPTIONS ?? {}),
1940
...(options ?? {}),
20-
} as Record<string, any>
41+
}
2142

2243
const fetchOptions = {
2344
manual,
@@ -29,26 +50,26 @@ function useRequestImplement<TData, TParams extends any[]>(
2950
const serviceRef = ref(service)
3051

3152
// reactive
32-
const state = reactive<{
33-
data?: TData
34-
loading: boolean
35-
params?: TParams
36-
error?: Error
37-
}>({
53+
const state = reactive<UseRequestFetchState<TData, TParams>>({
3854
data: initialData,
3955
loading: false,
4056
params: undefined,
4157
error: undefined,
4258
})
4359

44-
const setState = (s: any, field?: keyof typeof state) => {
60+
const setState = (currentState: unknown, field?: keyof typeof state) => {
4561
if (field) {
46-
state[field] = s
62+
// if (isUseRequestFetchStateKey<UnwrapRef<TData>, UnwrapRef<TParams>>(field, currentState)) {
63+
// state[field] = currentState as any
64+
// }
65+
state[field] = currentState as any
4766
} else {
48-
state.data = s.data
49-
state.loading = s.loading
50-
state.error = s.error
51-
state.params = s.params
67+
if (isUseRequestFetchState<UnwrapRef<TData>, UnwrapRef<TParams>>(currentState)) {
68+
state.data = currentState.data
69+
state.loading = currentState.loading
70+
state.error = currentState.error
71+
state.params = currentState.params
72+
}
5273
}
5374
}
5475

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
const isBrowser = !!(
2+
typeof window !== "undefined" &&
3+
window.document &&
4+
window.document.createElement
5+
);
6+
7+
export default isBrowser;
Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
1-
import isDocumentVisible from "./isDocumentVisible";
2-
import isOnline from "./isOnline";
3-
import { canUseDom } from "./utils";
1+
// from swr
2+
import isBrowser from './isBrowser'
3+
import isDocumentVisible from './isDocumentVisible'
4+
import isOnline from './isOnline'
45

5-
const listeners: any[] = [];
6+
type Listener = () => void
67

7-
function subscribe(listener: () => void) {
8-
listeners.push(listener);
8+
const listeners: Listener[] = []
9+
10+
function subscribe(listener: Listener) {
11+
listeners.push(listener)
912
return function unsubscribe() {
10-
const index = listeners.indexOf(listener);
11-
listeners.splice(index, 1);
12-
};
13+
const index = listeners.indexOf(listener)
14+
if (index > -1) {
15+
listeners.splice(index, 1)
16+
}
17+
}
1318
}
1419

15-
if (canUseDom()) {
20+
if (isBrowser) {
1621
const revalidate = () => {
17-
if (!isDocumentVisible() || !isOnline()) return;
22+
if (!isDocumentVisible() || !isOnline()) return
1823
for (let i = 0; i < listeners.length; i++) {
19-
const listener = listeners[i];
20-
listener();
24+
const listener = listeners[i]
25+
listener()
2126
}
22-
};
23-
window.addEventListener("visibilitychange", revalidate, false);
24-
window.addEventListener("focus", revalidate, false);
27+
}
28+
window.addEventListener('visibilitychange', revalidate, false)
29+
window.addEventListener('focus', revalidate, false)
2530
}
2631

27-
export default subscribe;
32+
export default subscribe

0 commit comments

Comments
 (0)