Skip to content

Commit 71bfad1

Browse files
authored
feat: v2 (#196) (#197)
* type: format result type * type: sync * type: format result type * chore: upgrade v2 * feat: upgrade use-request plugin * docs: add use-request format result docs * docs: add migrate v2 * docs: opt * docs: demo * docs: add route * test: use-request plugin unit test
1 parent 6e59ff7 commit 71bfad1

File tree

33 files changed

+490
-153
lines changed

33 files changed

+490
-153
lines changed

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@
3636
"@vue-hooks-plus/vitepress-demo-block": "workspace:^1.0.0",
3737
"@vue-hooks-plus/use-immer":"workspace:^1.0.0",
3838
"@vue-hooks-plus/use-worker":"workspace:^1.0.0",
39-
"@vue-hooks-plus/use-request":"workspace:^1.0.0",
40-
"@vue-hooks-plus/use-request-plugins":"workspace:^1.0.0",
41-
"@vue-hooks-plus/types":"workspace:^1.0.0",
39+
"@vue-hooks-plus/use-request":"workspace:^2.0.0",
40+
"@vue-hooks-plus/use-request-plugins":"workspace:^2.0.0",
41+
"@vue-hooks-plus/types":"workspace:^2.0.0",
4242
"@vue-hooks-plus/eslint-config":"workspace:^1.0.0",
4343
"@vue/test-utils": "^2.1.0",
4444
"@vitest/coverage-c8":"^0.25.7",

packages/hooks/docs/.vitepress/router.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,10 @@ const useRequestRouter = [
137137
text: '错误重试',
138138
link: '/useRequest/retry/',
139139
},
140-
140+
{
141+
text: '格式化数据',
142+
link: '/useRequest/formatResult/',
143+
},
141144
{
142145
text: '缓存 & SWR',
143146
link: '/useRequest/cache/',
@@ -155,7 +158,7 @@ const useRequestRouter = [
155158
link: '/useRequest/scroll/',
156159
},
157160
{
158-
text: '中间件·Beta',
161+
text: '中间件',
159162
link: '/useRequest/middleware/',
160163
},
161164
{
@@ -250,7 +253,10 @@ const useRequestRouterEN = [
250253
text: 'Retry',
251254
link: '/en/useRequest/retry/',
252255
},
253-
256+
{
257+
text: 'Format Result',
258+
link: '/en/useRequest/formatResult/',
259+
},
254260
{
255261
text: 'Cache & SWR',
256262
link: '/en/useRequest/cache/',
@@ -268,7 +274,7 @@ const useRequestRouterEN = [
268274
link: '/en/useRequest/scroll/',
269275
},
270276
{
271-
text: 'Middleware·Beta',
277+
text: 'Middleware',
272278
link: '/en/useRequest/middleware/',
273279
},
274280
{
@@ -310,6 +316,11 @@ export function getRouterConfig(langPrefix = '/') {
310316
text: langPrefix === '/' ? '📐 UseRequest规范' : '📐 UseRequest specification',
311317
link: `${langPrefix}useRequest/guide/`,
312318
},
319+
{
320+
text: langPrefix === '/' ? '🫶 迁移到 v2 版本' : '🫶 Migrate to v2 version',
321+
link: `${langPrefix}migrate/`,
322+
},
323+
313324
// {
314325
// text: langPrefix === '/' ? '🧑‍🏫 在线教程' : '🧑‍🏫 Online Teaching',
315326
// link: `${langPrefix}onlineTeaching/`,
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 🫶 Migrate to v2 version
2+
3+
:::info
4+
5+
- useRequest plugin option
6+
7+
:::
8+
9+
## 1、useRequest plugin option
10+
11+
In order to have good type hints and subsequent expansion in the v2 version of useRequest plug-in system, we have redesigned the usage of plugin option. You only need to make simple changes to achieve migration.
12+
13+
## v1 use
14+
15+
```typescript
16+
const { data } = useRequest(
17+
() => serviceFn(),
18+
{
19+
...option,
20+
...pluginOption,
21+
},
22+
[useFormatterPlugin, ...otherPlugins],
23+
)
24+
```
25+
26+
## v2 use
27+
28+
```typescript
29+
const { data } = useRequest(
30+
() => serviceFn(),
31+
{
32+
...option,
33+
pluginOptions: {
34+
...pluginOption,
35+
},
36+
},
37+
[useFormatterPlugin, ...otherPlugins],
38+
)
39+
```
40+
41+
Just migrate it to `pluginOptions` based on the original plugin option.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 🫶 迁移到 v2 版本
2+
3+
:::info
4+
5+
- useRequest plugin option
6+
7+
:::
8+
9+
## 1、useRequest plugin option
10+
11+
v2 版本的 useRequest 插件系统为了有良好的类型提示以及后续拓展,我们重新设计了 plugin option 的使用方式,你只需要进行简单的改变即可达到迁移。
12+
13+
## v1 use
14+
15+
```typescript
16+
const { data } = useRequest(
17+
() => serviceFn(),
18+
{
19+
...option,
20+
...pluginOption,
21+
},
22+
[useFormatterPlugin, ...otherPlugins],
23+
)
24+
```
25+
26+
## v2 use
27+
28+
```typescript
29+
const { data } = useRequest(
30+
() => serviceFn(),
31+
{
32+
...option,
33+
pluginOptions: {
34+
...pluginOption,
35+
},
36+
},
37+
[useFormatterPlugin, ...otherPlugins],
38+
)
39+
```
40+
41+
只需要在原来的 plugin option 的基础上,将其迁移到 `pluginOptions` 下即可。

packages/hooks/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",
3-
"version": "1.9.0",
3+
"version": "2.0.0",
44
"description": "Vue hooks library",
55
"files": [
66
"dist",

packages/hooks/src/useRequest/Fetch.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
UseRequestOptions,
66
UseRequestPluginReturn,
77
UseRequestService,
8+
UseRequestOptionsWithFormatResult
89
} from './types'
910

1011
export default class Fetch<TData, TParams extends unknown[] = any> {
@@ -23,7 +24,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
2324

2425
constructor(
2526
public serviceRef: Ref<UseRequestService<TData, TParams>>,
26-
public options: UseRequestOptions<TData, TParams, any>,
27+
public options: Partial<UseRequestOptions<TData, TParams, any> & UseRequestOptionsWithFormatResult<TData, TParams, any, any>>,
2728
public setUpdateData: (
2829
currentState: unknown,
2930
key?: keyof UseRequestFetchState<TData, TParams>,
@@ -116,7 +117,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
116117
)
117118
// Do you want to stop the request
118119
if (stopNow) {
119-
return new Promise(() => {})
120+
return new Promise(() => { })
120121
}
121122

122123
this.setState({
@@ -144,7 +145,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
144145
this.runPluginHandler('onError', error, params)
145146

146147
// Manually intercept the error and return a Promise with an empty status
147-
return new Promise(() => {})
148+
return new Promise(() => { })
148149
}
149150

150151
try {
@@ -154,7 +155,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
154155
const requestReturnResponse = (res: any) => {
155156
// The request has been cancelled, and the count will be inconsistent with the currentCount
156157
if (currentCount !== this.count) {
157-
return new Promise(() => {})
158+
return new Promise(() => { })
158159
}
159160
// Format data
160161
const formattedResult = this.options.formatResult ? this.options.formatResult(res) : res
@@ -188,7 +189,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
188189
return requestReturnResponse(servicePromiseResult)
189190
} catch (error) {
190191
if (currentCount !== this.count) {
191-
return new Promise(() => {})
192+
return new Promise(() => { })
192193
}
193194

194195
this.setState({

packages/hooks/src/useRequest/__tests__/plugin.spec.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ const useFormatterPlugin: UseRequestPlugin<
2424
{
2525
formatter?: (params?: { name: string; age: number }) => any
2626
}
27-
> = (fetchInstance, { formatter }) => {
27+
> = (fetchInstance, { pluginOptions }) => {
2828
return {
2929
onSuccess: () => {
30-
fetchInstance.setData(formatter?.(fetchInstance.state.data), 'data')
30+
fetchInstance.setData(pluginOptions?.formatter?.(fetchInstance.state.data), 'data')
3131
},
3232
}
3333
}
@@ -37,12 +37,14 @@ describe('useRequest/Plugin', () => {
3737
useRequest(
3838
() => getUsername(),
3939
{
40-
formatter: (data: any) => {
41-
return {
42-
name: `${data.name} - plugins update`,
43-
age: 20,
44-
}
45-
},
40+
pluginOptions: {
41+
formatter: (data) => {
42+
return {
43+
name: `${data?.name} - plugins update`,
44+
age: 20,
45+
}
46+
},
47+
}
4648
},
4749
[useFormatterPlugin],
4850
),

packages/hooks/src/useRequest/devtools/devtools.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { setupDevtoolsPlugin } from '@vue/devtools-api'
22

3-
import { unref } from 'vue'
43
import { getRequestTagBg } from './utils'
54
import devToolsStore from './store'
65
import Fetch from '../Fetch'
6+
import { unref } from 'vue'
77

88
const pluginId = 'vue-hooks-plus'
99
const pluginName = 'Vue Hooks Plus 🍭'
@@ -163,11 +163,11 @@ export function setupDevtools(app: any) {
163163
'Data Explorer': Object.keys(currentSource.instance.state).map(item => ({
164164
key: item,
165165
value:
166-
currentSource.instance.state[item as keyof typeof currentSource.instance.state],
166+
unref(currentSource.instance.state[item as keyof typeof currentSource.instance.state]),
167167
})),
168168
Option: Object.keys(currentSource.instance.options).map(item => ({
169169
key: item,
170-
value: unref(currentSource.instance.options[item]),
170+
value: currentSource.instance.options[item as keyof typeof currentSource.instance.options],
171171
})),
172172
["Plugins 🧩"]:
173173
currentSource.instance.pluginImpls?.map((_, index) => {

packages/hooks/src/useRequest/docs/basic/index.en-US.md

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ In the following example, we demonstrate a scenario of `mutate`.
113113

114114
We have modified the user name, but we do not want to wait for the request to be successful before giving feedback to the user. Instead, modify the data directly, then call the modify request in background, and provide additional feedback after the request returns.
115115

116-
### error rollback `1.7.7.alpha.4`
116+
### error rollback
117117

118118
When you use `mutate`, it is possible that the remote data change fails after the optimistic data is displayed to the user. In this case, you can enable `rollbackOnError`, which restores the local cache to its previous state, ensuring that the user sees Got the correct data.
119119

@@ -149,12 +149,6 @@ If we set `options.manual = false`, the parameters of calling `service` for the
149149
title=""
150150
desc=""> </demo>
151151

152-
## Format the request data
153-
154-
Since `useRequest` needs to guarantee a good plug-in system, format is too invasive for the system, the formatting here is `useFormatResult`, format data to `useFormatResult` after the request data is completed, `useFormatResult` can well support `typescript` type prompt. <br />
155-
156-
<a href="/docs/hooks/en/useFormatResult/" >Jump to useFormatResult</a>
157-
158152
## API
159153

160154
```ts
@@ -205,7 +199,7 @@ const {
205199
| initialData | Init data | `TData` \| `undefined` |
206200
| manual | <ul><li> The default is `false`. That is, the service is automatically executed during initialization.</li><li>If set to `true`, you need to manually call `run` or `runAsync` to trigger execution. </li></ul> | `boolean` | `false` |
207201
| defaultParams | The parameters passed to the service at the first default execution | `TParams` | - |
208-
| formatResult | Format the request results, which recommend to use `useFormatResult` | `(response: TData) => any` | - |
202+
| formatResult | Format the request results,v1 which recommend to use `useFormatResult` | `(response: TData) => FormatData` | - |
209203
| onBefore | Triggered before service execution | `(params: TParams) => void` | - |
210204
| onSuccess | Triggered when service resolve | `(data: TData, params: TParams) => void` | - |
211205
| onError | Triggered when service reject | `(e: Error, params: TParams) => void` | - |

packages/hooks/src/useRequest/docs/basic/index.zh-CN.md

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -146,12 +146,6 @@ runAsync()
146146
title=""
147147
desc=""> </demo>
148148

149-
## 格式化请求数据
150-
151-
由于 `useRequest` 需要保证良好的插件系统,format 对于系统来说侵入性太大,这里格式化使用的的是 `useFormatResult`,在请求数据完成后将 data 传入 `useFormatResult` 进行格式化, `useFormatResult` 可以很好的支持 `typescript` 类型提示。 <br />
152-
153-
<a href="/docs/hooks/useFormatResult/" >跳转至 useFormatResult</a>
154-
155149
## API
156150

157151
```ts
@@ -202,7 +196,7 @@ const {
202196
| initialData | 初始化的数据 | `TData` \| `undefined` |
203197
| manual | <ul><li> 默认 `false`。 即在初始化时自动执行 service。</li><li>如果设置为 `true`,则需要手动调用 `run``runAsync` 触发执行。 </li></ul> | `boolean` | `false` |
204198
| defaultParams | 首次默认执行时,传递给 service 的参数 | `TParams` | - |
205-
| formatResult | 格式化请求结果,建议使用 `useFormatResult` | `(response: TData) => any` | - |
199+
| formatResult | 格式化请求结果,v1 建议使用 `useFormatResult` | `(response: TData) => FormatData` | - |
206200
| onBefore | service 执行前触发 | `(params: TParams) => void` | - |
207201
| onSuccess | service resolve 时触发 | `(data: TData, params: TParams) => void` | - |
208202
| onError | service reject 时触发 | `(e: Error, params: TParams) => void` | - |

0 commit comments

Comments
 (0)