@ahoo-wang/fetcher-react 3.9.1 → 3.9.3
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 +184 -0
- package/README.zh-CN.md +184 -0
- package/dist/api/createExecuteApiHooks.d.ts +102 -0
- package/dist/api/createExecuteApiHooks.d.ts.map +1 -0
- package/dist/api/index.d.ts +2 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/core/useExecutePromise.d.ts +1 -1
- package/dist/core/useExecutePromise.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +668 -613
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,6 +21,7 @@ robust data fetching capabilities.
|
|
|
21
21
|
- ⚡ **Performance**: Optimized with useMemo, useCallback, and smart dependency management
|
|
22
22
|
- 🎯 **Options Flexibility**: Support for both static options and dynamic option suppliers
|
|
23
23
|
- 🔧 **Developer Experience**: Built-in loading states, error handling, and automatic re-rendering
|
|
24
|
+
- 🏗️ **API Hooks Generation**: Automatic type-safe React hooks generation from API objects
|
|
24
25
|
- 📊 **Advanced Query Hooks**: Specialized hooks for list, paged, single, count, and stream queries with state management
|
|
25
26
|
|
|
26
27
|
## Table of Contents
|
|
@@ -28,6 +29,7 @@ robust data fetching capabilities.
|
|
|
28
29
|
- [Installation](#installation)
|
|
29
30
|
- [Quick Start](#quick-start)
|
|
30
31
|
- [Usage](#usage)
|
|
32
|
+
- [API Hooks](#api-hooks)
|
|
31
33
|
- [Core Hooks](#core-hooks)
|
|
32
34
|
- [useExecutePromise](#useexecutepromise-hook)
|
|
33
35
|
- [usePromiseState](#usepromisestate-hook)
|
|
@@ -111,6 +113,188 @@ function App() {
|
|
|
111
113
|
|
|
112
114
|
## Usage
|
|
113
115
|
|
|
116
|
+
### API Hooks
|
|
117
|
+
|
|
118
|
+
#### createExecuteApiHooks
|
|
119
|
+
|
|
120
|
+
🚀 **Automatic Type-Safe API Hooks Generation** - Generate fully typed React hooks from API objects with automatic method discovery, class method support, and advanced execution control.
|
|
121
|
+
|
|
122
|
+
The `createExecuteApiHooks` function automatically discovers all function methods from an API object (including prototype chains for class instances) and creates corresponding React hooks with the naming pattern `use{CapitalizedMethodName}`. Each generated hook provides full state management, error handling, and supports custom execution callbacks with type-safe parameter access.
|
|
123
|
+
|
|
124
|
+
**Key Features:**
|
|
125
|
+
|
|
126
|
+
- **Automatic Method Discovery**: Traverses object properties and prototype chains
|
|
127
|
+
- **Type-Safe Hook Generation**: Full TypeScript inference for parameters and return types
|
|
128
|
+
- **Class Method Support**: Handles both static methods and class instances with `this` binding
|
|
129
|
+
- **Execution Control**: `onBeforeExecute` callback for parameter inspection/modification and abort controller access
|
|
130
|
+
- **Custom Error Types**: Support for specifying error types beyond the default `FetcherError`
|
|
131
|
+
|
|
132
|
+
```typescript jsx
|
|
133
|
+
import { createExecuteApiHooks } from '@ahoo-wang/fetcher-react';
|
|
134
|
+
|
|
135
|
+
// Define your API object (can be a class instance or plain object)
|
|
136
|
+
class UserApi {
|
|
137
|
+
async getUser(id: string): Promise<User> {
|
|
138
|
+
const response = await fetch(`/api/users/${id}`);
|
|
139
|
+
return response.json();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async createUser(data: { name: string; email: string }): Promise<User> {
|
|
143
|
+
const response = await fetch('/api/users', {
|
|
144
|
+
method: 'POST',
|
|
145
|
+
headers: { 'Content-Type': 'application/json' },
|
|
146
|
+
body: JSON.stringify(data),
|
|
147
|
+
});
|
|
148
|
+
return response.json();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async updateUser(id: string, updates: Partial<User>): Promise<User> {
|
|
152
|
+
const response = await fetch(`/api/users/${id}`, {
|
|
153
|
+
method: 'PATCH',
|
|
154
|
+
headers: { 'Content-Type': 'application/json' },
|
|
155
|
+
body: JSON.stringify(updates),
|
|
156
|
+
});
|
|
157
|
+
return response.json();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const userApi = new UserApi();
|
|
162
|
+
|
|
163
|
+
// Generate type-safe hooks
|
|
164
|
+
const apiHooks = createExecuteApiHooks({ api: userApi });
|
|
165
|
+
|
|
166
|
+
function UserComponent() {
|
|
167
|
+
// Hooks are automatically generated with proper typing
|
|
168
|
+
const { loading: getLoading, result: user, error: getError, execute: getUser } = apiHooks.useGetUser();
|
|
169
|
+
const { loading: createLoading, result: createdUser, error: createError, execute: createUser } = apiHooks.useCreateUser({
|
|
170
|
+
onBeforeExecute: (abortController, args) => {
|
|
171
|
+
// args is fully typed as [data: { name: string; email: string }]
|
|
172
|
+
const [data] = args;
|
|
173
|
+
// Modify parameters in place if needed
|
|
174
|
+
data.email = data.email.toLowerCase();
|
|
175
|
+
// Access abort controller for custom cancellation
|
|
176
|
+
abortController.signal.addEventListener('abort', () => {
|
|
177
|
+
console.log('User creation cancelled');
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const handleFetchUser = (userId: string) => {
|
|
183
|
+
getUser(userId); // Fully typed - only accepts string parameter
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const handleCreateUser = (userData: { name: string; email: string }) => {
|
|
187
|
+
createUser(userData); // Fully typed - only accepts correct data shape
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
return (
|
|
191
|
+
<div>
|
|
192
|
+
<button onClick={() => handleFetchUser('123')}>
|
|
193
|
+
Fetch User
|
|
194
|
+
</button>
|
|
195
|
+
{getLoading && <div>Loading user...</div>}
|
|
196
|
+
{getError && <div>Error: {getError.message}</div>}
|
|
197
|
+
{user && <div>User: {user.name}</div>}
|
|
198
|
+
|
|
199
|
+
<button onClick={() => handleCreateUser({ name: 'John', email: 'john@example.com' })}>
|
|
200
|
+
Create User
|
|
201
|
+
</button>
|
|
202
|
+
{createLoading && <div>Creating user...</div>}
|
|
203
|
+
{createError && <div>Error: {createError.message}</div>}
|
|
204
|
+
{createdUser && <div>Created: {createdUser.name}</div>}
|
|
205
|
+
</div>
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
**Custom Error Types:**
|
|
211
|
+
|
|
212
|
+
```typescript jsx
|
|
213
|
+
import { createExecuteApiHooks } from '@ahoo-wang/fetcher-react';
|
|
214
|
+
|
|
215
|
+
// Define custom error type
|
|
216
|
+
class ApiError extends Error {
|
|
217
|
+
constructor(
|
|
218
|
+
public statusCode: number,
|
|
219
|
+
message: string,
|
|
220
|
+
) {
|
|
221
|
+
super(message);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Generate hooks with custom error type
|
|
226
|
+
const apiHooks = createExecuteApiHooks<
|
|
227
|
+
{ getData: (id: string) => Promise<Data> },
|
|
228
|
+
ApiError
|
|
229
|
+
>({
|
|
230
|
+
api: { getData },
|
|
231
|
+
errorType: ApiError,
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
function MyComponent() {
|
|
235
|
+
const { error, execute } = apiHooks.useGetData();
|
|
236
|
+
|
|
237
|
+
// error is now typed as ApiError | undefined
|
|
238
|
+
if (error) {
|
|
239
|
+
console.log('Status code:', error.statusCode); // TypeScript knows about statusCode
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
**Advanced Usage with Class Methods:**
|
|
245
|
+
|
|
246
|
+
```typescript jsx
|
|
247
|
+
import { createExecuteApiHooks } from '@ahoo-wang/fetcher-react';
|
|
248
|
+
|
|
249
|
+
class ApiClient {
|
|
250
|
+
private baseUrl: string;
|
|
251
|
+
|
|
252
|
+
constructor(baseUrl: string) {
|
|
253
|
+
this.baseUrl = baseUrl;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async get(endpoint: string): Promise<any> {
|
|
257
|
+
const response = await fetch(`${this.baseUrl}${endpoint}`);
|
|
258
|
+
return response.json();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async post(endpoint: string, data: any): Promise<any> {
|
|
262
|
+
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
|
263
|
+
method: 'POST',
|
|
264
|
+
headers: { 'Content-Type': 'application/json' },
|
|
265
|
+
body: JSON.stringify(data),
|
|
266
|
+
});
|
|
267
|
+
return response.json();
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Static method example
|
|
271
|
+
static async healthCheck(): Promise<{ status: string }> {
|
|
272
|
+
const response = await fetch('/api/health');
|
|
273
|
+
return response.json();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const apiClient = new ApiClient('/api');
|
|
278
|
+
const apiHooks = createExecuteApiHooks({ api: apiClient });
|
|
279
|
+
|
|
280
|
+
// Generated hooks: useGet, usePost
|
|
281
|
+
// Static methods are also discovered: useHealthCheck
|
|
282
|
+
|
|
283
|
+
function ApiComponent() {
|
|
284
|
+
const { execute: getData } = apiHooks.useGet();
|
|
285
|
+
const { execute: postData } = apiHooks.usePost();
|
|
286
|
+
const { execute: healthCheck } = apiHooks.useHealthCheck();
|
|
287
|
+
|
|
288
|
+
return (
|
|
289
|
+
<div>
|
|
290
|
+
<button onClick={() => getData('/users')}>Get Users</button>
|
|
291
|
+
<button onClick={() => postData('/users', { name: 'New User' })}>Create User</button>
|
|
292
|
+
<button onClick={() => healthCheck()}>Health Check</button>
|
|
293
|
+
</div>
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
|
|
114
298
|
### Core Hooks
|
|
115
299
|
|
|
116
300
|
#### useExecutePromise Hook
|
package/README.zh-CN.md
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
- ⚡ **性能优化**: 使用 useMemo、useCallback 和智能依赖管理进行优化
|
|
20
20
|
- 🎯 **选项灵活性**: 支持静态选项和动态选项供应商
|
|
21
21
|
- 🔧 **开发者体验**: 内置加载状态、错误处理和自动重新渲染
|
|
22
|
+
- 🏗️ **API Hooks 生成**: 从 API 对象自动生成类型安全的 React hooks
|
|
22
23
|
- 📊 **高级查询 Hooks**: 专门用于列表、分页、单个、计数和流查询的 hooks,具有状态管理功能
|
|
23
24
|
|
|
24
25
|
## 目录
|
|
@@ -26,6 +27,7 @@
|
|
|
26
27
|
- [安装](#安装)
|
|
27
28
|
- [快速开始](#快速开始)
|
|
28
29
|
- [使用方法](#使用方法)
|
|
30
|
+
- [API Hooks](#api-hooks)
|
|
29
31
|
- [核心 Hooks](#核心-hooks)
|
|
30
32
|
- [useExecutePromise](#useexecutepromise)
|
|
31
33
|
- [usePromiseState](#usepromisestate)
|
|
@@ -109,6 +111,188 @@ function App() {
|
|
|
109
111
|
|
|
110
112
|
## 使用方法
|
|
111
113
|
|
|
114
|
+
### API Hooks
|
|
115
|
+
|
|
116
|
+
#### createExecuteApiHooks
|
|
117
|
+
|
|
118
|
+
🚀 **自动类型安全 API Hooks 生成** - 从 API 对象自动生成完全类型化的 React hooks,具有自动方法发现、类方法支持和高级执行控制。
|
|
119
|
+
|
|
120
|
+
`createExecuteApiHooks` 函数自动发现 API 对象中的所有函数方法(包括类实例的原型链),并使用命名模式 `use{首字母大写的方法名}` 创建相应的 React hooks。每个生成的 hook 都提供完整的状态管理、错误处理,并支持具有类型安全参数访问的自定义执行回调。
|
|
121
|
+
|
|
122
|
+
**主要特性:**
|
|
123
|
+
|
|
124
|
+
- **自动方法发现**:遍历对象属性和原型链
|
|
125
|
+
- **类型安全 Hook 生成**:参数和返回类型的完整 TypeScript 推断
|
|
126
|
+
- **类方法支持**:处理静态方法和具有 `this` 绑定的类实例
|
|
127
|
+
- **执行控制**:`onBeforeExecute` 回调用于参数检查/修改和中止控制器访问
|
|
128
|
+
- **自定义错误类型**:支持指定超出默认 `FetcherError` 的错误类型
|
|
129
|
+
|
|
130
|
+
```typescript jsx
|
|
131
|
+
import { createExecuteApiHooks } from '@ahoo-wang/fetcher-react';
|
|
132
|
+
|
|
133
|
+
// 定义您的 API 对象(可以是类实例或普通对象)
|
|
134
|
+
class UserApi {
|
|
135
|
+
async getUser(id: string): Promise<User> {
|
|
136
|
+
const response = await fetch(`/api/users/${id}`);
|
|
137
|
+
return response.json();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async createUser(data: { name: string; email: string }): Promise<User> {
|
|
141
|
+
const response = await fetch('/api/users', {
|
|
142
|
+
method: 'POST',
|
|
143
|
+
headers: { 'Content-Type': 'application/json' },
|
|
144
|
+
body: JSON.stringify(data),
|
|
145
|
+
});
|
|
146
|
+
return response.json();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async updateUser(id: string, updates: Partial<User>): Promise<User> {
|
|
150
|
+
const response = await fetch(`/api/users/${id}`, {
|
|
151
|
+
method: 'PATCH',
|
|
152
|
+
headers: { 'Content-Type': 'application/json' },
|
|
153
|
+
body: JSON.stringify(updates),
|
|
154
|
+
});
|
|
155
|
+
return response.json();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const userApi = new UserApi();
|
|
160
|
+
|
|
161
|
+
// 生成类型安全的 hooks
|
|
162
|
+
const apiHooks = createExecuteApiHooks({ api: userApi });
|
|
163
|
+
|
|
164
|
+
function UserComponent() {
|
|
165
|
+
// Hooks 自动生成,具有正确的类型
|
|
166
|
+
const { loading: getLoading, result: user, error: getError, execute: getUser } = apiHooks.useGetUser();
|
|
167
|
+
const { loading: createLoading, result: createdUser, error: createError, execute: createUser } = apiHooks.useCreateUser({
|
|
168
|
+
onBeforeExecute: (abortController, args) => {
|
|
169
|
+
// args 完全类型化为 [data: { name: string; email: string }]
|
|
170
|
+
const [data] = args;
|
|
171
|
+
// 如果需要,可以就地修改参数
|
|
172
|
+
data.email = data.email.toLowerCase();
|
|
173
|
+
// 访问中止控制器以进行自定义取消
|
|
174
|
+
abortController.signal.addEventListener('abort', () => {
|
|
175
|
+
console.log('用户创建已取消');
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
const handleFetchUser = (userId: string) => {
|
|
181
|
+
getUser(userId); // 完全类型化 - 仅接受字符串参数
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const handleCreateUser = (userData: { name: string; email: string }) => {
|
|
185
|
+
createUser(userData); // 完全类型化 - 仅接受正确的数据形状
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
return (
|
|
189
|
+
<div>
|
|
190
|
+
<button onClick={() => handleFetchUser('123')}>
|
|
191
|
+
获取用户
|
|
192
|
+
</button>
|
|
193
|
+
{getLoading && <div>正在加载用户...</div>}
|
|
194
|
+
{getError && <div>错误: {getError.message}</div>}
|
|
195
|
+
{user && <div>用户: {user.name}</div>}
|
|
196
|
+
|
|
197
|
+
<button onClick={() => handleCreateUser({ name: 'John', email: 'john@example.com' })}>
|
|
198
|
+
创建用户
|
|
199
|
+
</button>
|
|
200
|
+
{createLoading && <div>正在创建用户...</div>}
|
|
201
|
+
{createError && <div>错误: {createError.message}</div>}
|
|
202
|
+
{createdUser && <div>已创建: {createdUser.name}</div>}
|
|
203
|
+
</div>
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
**自定义错误类型:**
|
|
209
|
+
|
|
210
|
+
```typescript jsx
|
|
211
|
+
import { createExecuteApiHooks } from '@ahoo-wang/fetcher-react';
|
|
212
|
+
|
|
213
|
+
// 定义自定义错误类型
|
|
214
|
+
class ApiError extends Error {
|
|
215
|
+
constructor(
|
|
216
|
+
public statusCode: number,
|
|
217
|
+
message: string,
|
|
218
|
+
) {
|
|
219
|
+
super(message);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// 使用自定义错误类型生成 hooks
|
|
224
|
+
const apiHooks = createExecuteApiHooks<
|
|
225
|
+
{ getData: (id: string) => Promise<Data> },
|
|
226
|
+
ApiError
|
|
227
|
+
>({
|
|
228
|
+
api: { getData },
|
|
229
|
+
errorType: ApiError,
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
function MyComponent() {
|
|
233
|
+
const { error, execute } = apiHooks.useGetData();
|
|
234
|
+
|
|
235
|
+
// error 现在类型化为 ApiError | undefined
|
|
236
|
+
if (error) {
|
|
237
|
+
console.log('状态码:', error.statusCode); // TypeScript 知道 statusCode
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**具有类方法的高级用法:**
|
|
243
|
+
|
|
244
|
+
```typescript jsx
|
|
245
|
+
import { createExecuteApiHooks } from '@ahoo-wang/fetcher-react';
|
|
246
|
+
|
|
247
|
+
class ApiClient {
|
|
248
|
+
private baseUrl: string;
|
|
249
|
+
|
|
250
|
+
constructor(baseUrl: string) {
|
|
251
|
+
this.baseUrl = baseUrl;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async get(endpoint: string): Promise<any> {
|
|
255
|
+
const response = await fetch(`${this.baseUrl}${endpoint}`);
|
|
256
|
+
return response.json();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async post(endpoint: string, data: any): Promise<any> {
|
|
260
|
+
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
|
261
|
+
method: 'POST',
|
|
262
|
+
headers: { 'Content-Type': 'application/json' },
|
|
263
|
+
body: JSON.stringify(data),
|
|
264
|
+
});
|
|
265
|
+
return response.json();
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// 静态方法示例
|
|
269
|
+
static async healthCheck(): Promise<{ status: string }> {
|
|
270
|
+
const response = await fetch('/api/health');
|
|
271
|
+
return response.json();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const apiClient = new ApiClient('/api');
|
|
276
|
+
const apiHooks = createExecuteApiHooks({ api: apiClient });
|
|
277
|
+
|
|
278
|
+
// 生成的 hooks: useGet, usePost
|
|
279
|
+
// 静态方法也会被发现: useHealthCheck
|
|
280
|
+
|
|
281
|
+
function ApiComponent() {
|
|
282
|
+
const { execute: getData } = apiHooks.useGet();
|
|
283
|
+
const { execute: postData } = apiHooks.usePost();
|
|
284
|
+
const { execute: healthCheck } = apiHooks.useHealthCheck();
|
|
285
|
+
|
|
286
|
+
return (
|
|
287
|
+
<div>
|
|
288
|
+
<button onClick={() => getData('/users')}>获取用户</button>
|
|
289
|
+
<button onClick={() => postData('/users', { name: '新用户' })}>创建用户</button>
|
|
290
|
+
<button onClick={() => healthCheck()}>健康检查</button>
|
|
291
|
+
</div>
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
112
296
|
### 核心 Hooks
|
|
113
297
|
|
|
114
298
|
#### useExecutePromise
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { UseExecutePromiseReturn, UseExecutePromiseOptions } from '../core';
|
|
2
|
+
import { FetcherError } from '@ahoo-wang/fetcher';
|
|
3
|
+
/**
|
|
4
|
+
* Configuration options for createExecuteApiHooks.
|
|
5
|
+
* @template API - The API object type containing methods that return promises.
|
|
6
|
+
*/
|
|
7
|
+
export interface CreateExecuteApiHooksOptions<API extends Record<string, any>> {
|
|
8
|
+
/**
|
|
9
|
+
* The API object containing methods to be wrapped into hooks.
|
|
10
|
+
*/
|
|
11
|
+
api: API;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Options for useApiMethodExecute hook.
|
|
15
|
+
* @template TArgs - The parameter types of the API method.
|
|
16
|
+
* @template TData - The return type of the API method (resolved).
|
|
17
|
+
* @template E - The error type.
|
|
18
|
+
*/
|
|
19
|
+
export interface UseApiMethodExecuteOptions<TArgs = any[], TData = any, E = FetcherError> extends UseExecutePromiseOptions<TData, E> {
|
|
20
|
+
/**
|
|
21
|
+
* Callback executed before method invocation.
|
|
22
|
+
* Allows users to handle abortController and inspect/modify parameters.
|
|
23
|
+
* Note: Parameters can be modified in place for objects/arrays.
|
|
24
|
+
* @param abortController - The AbortController for the request.
|
|
25
|
+
* @param args - The arguments passed to the API method (type-safe).
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* onBeforeExecute: (abortController, args) => {
|
|
29
|
+
* // args is now typed as Parameters<TMethod>
|
|
30
|
+
* const [id, options] = args;
|
|
31
|
+
* // Modify parameters in place
|
|
32
|
+
* if (options && typeof options === 'object') {
|
|
33
|
+
* options.timestamp = Date.now();
|
|
34
|
+
* }
|
|
35
|
+
* }
|
|
36
|
+
*/
|
|
37
|
+
onBeforeExecute?: (abortController: AbortController, args: TArgs) => void;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The return type of createExecuteApiHooks.
|
|
41
|
+
* Creates a hook for each function method in the API object, prefixed with 'use' and capitalized.
|
|
42
|
+
* Each hook accepts optional useExecutepromise options and returns the useExecutepromise interface
|
|
43
|
+
* with a modified execute function that takes the API method parameters instead of a promise supplier.
|
|
44
|
+
* @template API - The API object type.
|
|
45
|
+
* @template E - The error type for all hooks (defaults to FetcherError).
|
|
46
|
+
*/
|
|
47
|
+
export type APIHooks<API extends Record<string, any>, E = FetcherError> = {
|
|
48
|
+
[K in keyof API as API[K] extends (...args: any[]) => Promise<any> ? `use${Capitalize<string & K>}` : never]: API[K] extends (...args: any[]) => Promise<any> ? (options?: UseApiMethodExecuteOptions<Parameters<API[K]>, Awaited<ReturnType<API[K]>>, E>) => UseExecutePromiseReturn<Awaited<ReturnType<API[K]>>, E> & {
|
|
49
|
+
execute: (...params: Parameters<API[K]>) => Promise<void>;
|
|
50
|
+
} : never;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Creates type-safe React hooks for API methods.
|
|
54
|
+
* Each API method that returns a Promise is wrapped into a hook that extends useExecutePromise.
|
|
55
|
+
* The generated hooks provide automatic state management, abort support, and error handling.
|
|
56
|
+
*
|
|
57
|
+
* @template API - The API object type containing methods that return promises.
|
|
58
|
+
* @param options - Configuration options including the API object.
|
|
59
|
+
* @returns An object containing hooks for each API method.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```typescript
|
|
63
|
+
* // Default behavior (no onBeforeExecute)
|
|
64
|
+
* const userApi = {
|
|
65
|
+
* getUser: (id: string) => fetch(`/api/users/${id}`).then(res => res.json()),
|
|
66
|
+
* createUser: (data: UserInput) => fetch('/api/users', {
|
|
67
|
+
* method: 'POST',
|
|
68
|
+
* body: JSON.stringify(data),
|
|
69
|
+
* }).then(res => res.json()),
|
|
70
|
+
* };
|
|
71
|
+
*
|
|
72
|
+
* const apiHooks = createExecuteApiHooks({ api: userApi });
|
|
73
|
+
*
|
|
74
|
+
* function UserComponent() {
|
|
75
|
+
* const { loading, result, error, execute } = apiHooks.useGetUser();
|
|
76
|
+
*
|
|
77
|
+
* const handleFetchUser = (userId: string) => {
|
|
78
|
+
* execute(userId); // Calls getUser(userId) directly
|
|
79
|
+
* };
|
|
80
|
+
*
|
|
81
|
+
* // Custom onBeforeExecute to handle abortController and modify parameters
|
|
82
|
+
* const { execute: customExecute } = apiHooks.useCreateUser({
|
|
83
|
+
* onBeforeExecute: (abortController, args) => {
|
|
84
|
+
* // args is now fully type-safe as Parameters<createUser>
|
|
85
|
+
* const [data] = args;
|
|
86
|
+
* // Modify parameters in place (assuming data is mutable)
|
|
87
|
+
* if (data && typeof data === 'object') {
|
|
88
|
+
* (data as any).timestamp = Date.now();
|
|
89
|
+
* }
|
|
90
|
+
* // Could also set up abortController.signal
|
|
91
|
+
* abortController.signal.addEventListener('abort', () => {
|
|
92
|
+
* console.log('Request aborted');
|
|
93
|
+
* });
|
|
94
|
+
* },
|
|
95
|
+
* });
|
|
96
|
+
*
|
|
97
|
+
* // ... component logic
|
|
98
|
+
* }
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
export declare function createExecuteApiHooks<API extends Record<string, any>, E = FetcherError>(options: CreateExecuteApiHooksOptions<API>): APIHooks<API, E>;
|
|
102
|
+
//# sourceMappingURL=createExecuteApiHooks.d.ts.map
|
|
@@ -0,0 +1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C,CAAC,EAC3B,CAAC,CACF,KACE,uBAAuB,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG;QAC7D,OAAO,EAAE,CAAC,GAAG,MAAM,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KAC3D,GACC,KAAK;CACV,CAAC;AAkGF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,wBAAgB,qBAAqB,CACnC,GAAG,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC/B,CAAC,GAAG,YAAY,EAChB,OAAO,EAAE,4BAA4B,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC,CAa9D"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAaA,cAAc,yBAAyB,CAAC"}
|
|
@@ -5,7 +5,7 @@ import { FetcherError } from '@ahoo-wang/fetcher';
|
|
|
5
5
|
* @template R - The type of the resolved value from the promise.
|
|
6
6
|
* @template E - The type of the error value, defaults to unknown.
|
|
7
7
|
*/
|
|
8
|
-
export interface UseExecutePromiseOptions<R, E =
|
|
8
|
+
export interface UseExecutePromiseOptions<R, E = FetcherError> extends UsePromiseStateOptions<R, E> {
|
|
9
9
|
/**
|
|
10
10
|
* Whether to propagate errors thrown by the promise.
|
|
11
11
|
* If true, the execute function will throw errors.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useExecutePromise.d.ts","sourceRoot":"","sources":["../../src/core/useExecutePromise.ts"],"names":[],"mappings":"AAeA,OAAO,EAEL,YAAY,EACZ,sBAAsB,EACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,C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,EAAE,CAAC,GAAG,YAAY,EAC7D,OAAO,CAAC,EAAE,wBAAwB,CAAC,CAAC,EAAE,CAAC,CAAC,GACvC,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC,CA0H/B"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC"}
|