@agentuity/react 0.0.69 → 0.0.70
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/dist/api.d.ts +196 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +325 -0
- package/dist/api.js.map +1 -0
- package/dist/env.d.ts.map +1 -1
- package/dist/env.js +3 -0
- package/dist/env.js.map +1 -1
- package/dist/eventstream.d.ts +52 -13
- package/dist/eventstream.d.ts.map +1 -1
- package/dist/eventstream.js +45 -13
- package/dist/eventstream.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/memo.d.ts +7 -0
- package/dist/memo.d.ts.map +1 -0
- package/dist/memo.js +32 -0
- package/dist/memo.js.map +1 -0
- package/dist/serialization.d.ts.map +1 -1
- package/dist/serialization.js +5 -7
- package/dist/serialization.js.map +1 -1
- package/dist/types.d.ts +10 -25
- package/dist/types.d.ts.map +1 -1
- package/dist/url.d.ts.map +1 -1
- package/dist/url.js +6 -0
- package/dist/url.js.map +1 -1
- package/dist/websocket.d.ts +60 -13
- package/dist/websocket.d.ts.map +1 -1
- package/dist/websocket.js +47 -13
- package/dist/websocket.js.map +1 -1
- package/package.json +3 -2
- package/src/api.ts +529 -0
- package/src/env.ts +3 -0
- package/src/eventstream.ts +87 -40
- package/src/index.ts +2 -1
- package/src/memo.ts +32 -0
- package/src/serialization.ts +4 -6
- package/src/types.ts +19 -29
- package/src/url.ts +7 -0
- package/src/websocket.ts +109 -43
- package/dist/run.d.ts +0 -34
- package/dist/run.d.ts.map +0 -1
- package/dist/run.js +0 -68
- package/dist/run.js.map +0 -1
- package/src/run.ts +0 -119
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentuity/react",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.70",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"author": "Agentuity employees and contributors",
|
|
6
6
|
"type": "module",
|
|
@@ -22,10 +22,11 @@
|
|
|
22
22
|
"clean": "rm -rf dist",
|
|
23
23
|
"build": "bunx tsc --build --force",
|
|
24
24
|
"typecheck": "bunx tsc --noEmit",
|
|
25
|
+
"test": "bun test",
|
|
25
26
|
"prepublishOnly": "bun run clean && bun run build"
|
|
26
27
|
},
|
|
27
28
|
"dependencies": {
|
|
28
|
-
"@agentuity/core": "0.0.
|
|
29
|
+
"@agentuity/core": "0.0.70"
|
|
29
30
|
},
|
|
30
31
|
"devDependencies": {
|
|
31
32
|
"@types/bun": "latest",
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
|
|
3
|
+
import type { InferInput, InferOutput } from '@agentuity/core';
|
|
4
|
+
import { AgentuityContext } from './context';
|
|
5
|
+
import { deserializeData } from './serialization';
|
|
6
|
+
import { buildUrl } from './url';
|
|
7
|
+
import type { RouteRegistry } from './types';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Extract route keys from RouteRegistry (e.g., 'GET /users', 'POST /users')
|
|
11
|
+
*/
|
|
12
|
+
export type RouteKey = keyof RouteRegistry;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Extract HTTP method from route key
|
|
16
|
+
*/
|
|
17
|
+
export type ExtractMethod<TRoute extends RouteKey> = TRoute extends `${infer Method} ${string}`
|
|
18
|
+
? Method
|
|
19
|
+
: never;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Extract input type for a specific route
|
|
23
|
+
*/
|
|
24
|
+
export type RouteInput<TRoute extends RouteKey> = TRoute extends keyof RouteRegistry
|
|
25
|
+
? RouteRegistry[TRoute] extends { inputSchema: any }
|
|
26
|
+
? InferInput<RouteRegistry[TRoute]['inputSchema']>
|
|
27
|
+
: never
|
|
28
|
+
: never;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Extract output type for a specific route
|
|
32
|
+
* Returns void if no outputSchema is defined (e.g., 204 No Content)
|
|
33
|
+
*/
|
|
34
|
+
export type RouteOutput<TRoute extends RouteKey> = TRoute extends keyof RouteRegistry
|
|
35
|
+
? RouteRegistry[TRoute] extends { outputSchema: infer TSchema }
|
|
36
|
+
? TSchema extends undefined | never
|
|
37
|
+
? void
|
|
38
|
+
: InferOutput<TSchema>
|
|
39
|
+
: void
|
|
40
|
+
: void;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Common options shared by all UseAPI configurations
|
|
44
|
+
*/
|
|
45
|
+
type UseAPICommonOptions<TRoute extends RouteKey> = {
|
|
46
|
+
/** Additional query parameters */
|
|
47
|
+
query?: URLSearchParams | Record<string, string>;
|
|
48
|
+
/** Additional request headers */
|
|
49
|
+
headers?: Record<string, string>;
|
|
50
|
+
/** Whether to execute the request immediately on mount (default: true for GET, false for others) */
|
|
51
|
+
enabled?: boolean;
|
|
52
|
+
/** How long data stays fresh before refetching (ms, default: 0 - always stale) */
|
|
53
|
+
staleTime?: number;
|
|
54
|
+
/** Refetch interval in milliseconds (default: disabled) */
|
|
55
|
+
refetchInterval?: number;
|
|
56
|
+
/** Callback when request succeeds */
|
|
57
|
+
onSuccess?: (data: RouteOutput<TRoute>) => void;
|
|
58
|
+
/** Callback when request fails */
|
|
59
|
+
onError?: (error: Error) => void;
|
|
60
|
+
} & (ExtractMethod<TRoute> extends 'GET'
|
|
61
|
+
? {
|
|
62
|
+
/** GET requests cannot have input (use query params instead) */
|
|
63
|
+
input?: never;
|
|
64
|
+
}
|
|
65
|
+
: {
|
|
66
|
+
/** Input data for the request (required for POST/PUT/PATCH/DELETE) */
|
|
67
|
+
input?: RouteInput<TRoute>;
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Options with route property (e.g., { route: 'GET /users' })
|
|
72
|
+
*/
|
|
73
|
+
type UseAPIOptionsWithRoute<TRoute extends RouteKey> = UseAPICommonOptions<TRoute> & {
|
|
74
|
+
/** Route key (e.g., 'GET /users', 'POST /users') */
|
|
75
|
+
route: TRoute;
|
|
76
|
+
/** Method cannot be specified when using route */
|
|
77
|
+
method?: never;
|
|
78
|
+
/** Path cannot be specified when using route */
|
|
79
|
+
path?: never;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Options with method and path properties (e.g., { method: 'GET', path: '/users' })
|
|
84
|
+
*/
|
|
85
|
+
type UseAPIOptionsWithMethodPath<TRoute extends RouteKey> = UseAPICommonOptions<TRoute> & {
|
|
86
|
+
/** HTTP method (e.g., 'GET', 'POST') */
|
|
87
|
+
method: ExtractMethod<TRoute>;
|
|
88
|
+
/** Request path (e.g., '/users') */
|
|
89
|
+
path: string;
|
|
90
|
+
/** Route cannot be specified when using method/path */
|
|
91
|
+
route?: never;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Options for useAPI hook with smart input typing based on HTTP method
|
|
96
|
+
* Supports either route OR {method, path} but not both
|
|
97
|
+
*/
|
|
98
|
+
export type UseAPIOptions<TRoute extends RouteKey> =
|
|
99
|
+
| UseAPIOptionsWithRoute<TRoute>
|
|
100
|
+
| UseAPIOptionsWithMethodPath<TRoute>;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Base return value from useAPI hook (without data property or execute)
|
|
104
|
+
*/
|
|
105
|
+
interface UseAPIResultBase {
|
|
106
|
+
/** Error if request failed */
|
|
107
|
+
error: Error | null;
|
|
108
|
+
/** Whether request is currently in progress */
|
|
109
|
+
isLoading: boolean;
|
|
110
|
+
/** Whether request has completed successfully at least once */
|
|
111
|
+
isSuccess: boolean;
|
|
112
|
+
/** Whether request has failed */
|
|
113
|
+
isError: boolean;
|
|
114
|
+
/** Whether data is currently being fetched (including refetches) */
|
|
115
|
+
isFetching: boolean;
|
|
116
|
+
/** Reset state to initial values */
|
|
117
|
+
reset: () => void;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Return value for GET requests (auto-executing)
|
|
122
|
+
*/
|
|
123
|
+
type UseAPIResultQuery<TRoute extends RouteKey> = UseAPIResultBase &
|
|
124
|
+
(RouteOutput<TRoute> extends void
|
|
125
|
+
? {
|
|
126
|
+
/** No data property - route returns no content (204 No Content) */
|
|
127
|
+
data?: never;
|
|
128
|
+
/** Manually trigger a refetch */
|
|
129
|
+
refetch: () => Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
: {
|
|
132
|
+
/** Response data (undefined until loaded) */
|
|
133
|
+
data: RouteOutput<TRoute> | undefined;
|
|
134
|
+
/** Manually trigger a refetch */
|
|
135
|
+
refetch: () => Promise<void>;
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Return value for POST/PUT/PATCH/DELETE requests (manual execution)
|
|
140
|
+
*/
|
|
141
|
+
type UseAPIResultMutation<TRoute extends RouteKey> = UseAPIResultBase &
|
|
142
|
+
(RouteOutput<TRoute> extends void
|
|
143
|
+
? {
|
|
144
|
+
/** No data property - route returns no content (204 No Content) */
|
|
145
|
+
data?: never;
|
|
146
|
+
/** Invoke the mutation with required input */
|
|
147
|
+
invoke: RouteInput<TRoute> extends never
|
|
148
|
+
? () => Promise<void>
|
|
149
|
+
: (input: RouteInput<TRoute>) => Promise<void>;
|
|
150
|
+
}
|
|
151
|
+
: {
|
|
152
|
+
/** Response data (undefined until invoked) */
|
|
153
|
+
data: RouteOutput<TRoute> | undefined;
|
|
154
|
+
/** Invoke the mutation with required input */
|
|
155
|
+
invoke: RouteInput<TRoute> extends never
|
|
156
|
+
? () => Promise<RouteOutput<TRoute>>
|
|
157
|
+
: (input: RouteInput<TRoute>) => Promise<RouteOutput<TRoute>>;
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Return value from useAPI hook
|
|
162
|
+
* - GET requests: Auto-executes, returns refetch()
|
|
163
|
+
* - POST/PUT/PATCH/DELETE: Manual execution, returns execute(input)
|
|
164
|
+
*/
|
|
165
|
+
export type UseAPIResult<TRoute extends RouteKey> =
|
|
166
|
+
ExtractMethod<TRoute> extends 'GET' ? UseAPIResultQuery<TRoute> : UseAPIResultMutation<TRoute>;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Parse route key into method and path
|
|
170
|
+
*/
|
|
171
|
+
function parseRouteKey(routeKey: string): { method: string; path: string } {
|
|
172
|
+
const parts = routeKey.split(' ');
|
|
173
|
+
if (parts.length !== 2) {
|
|
174
|
+
throw new Error(`Invalid route key format: "${routeKey}". Expected "METHOD /path"`);
|
|
175
|
+
}
|
|
176
|
+
return { method: parts[0], path: parts[1] };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Convert query object to URLSearchParams
|
|
181
|
+
*/
|
|
182
|
+
function toSearchParams(
|
|
183
|
+
query?: URLSearchParams | Record<string, string>
|
|
184
|
+
): URLSearchParams | undefined {
|
|
185
|
+
if (!query) return undefined;
|
|
186
|
+
if (query instanceof URLSearchParams) return query;
|
|
187
|
+
return new URLSearchParams(query);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Type-safe API client hook with TanStack Query-inspired features.
|
|
192
|
+
*
|
|
193
|
+
* Provides automatic type inference for route inputs and outputs based on
|
|
194
|
+
* the RouteRegistry generated from your routes.
|
|
195
|
+
*
|
|
196
|
+
* **Smart input typing:**
|
|
197
|
+
* - GET requests: `input` is `never` (use `query` params instead)
|
|
198
|
+
* - POST/PUT/PATCH/DELETE: `input` is properly typed from route schema
|
|
199
|
+
*
|
|
200
|
+
* @template TRoute - Route key from RouteRegistry (e.g., 'GET /users')
|
|
201
|
+
*
|
|
202
|
+
* @example Simple GET request with string
|
|
203
|
+
* ```typescript
|
|
204
|
+
* const { data, isLoading } = useAPI('GET /users');
|
|
205
|
+
* ```
|
|
206
|
+
*
|
|
207
|
+
* @example GET request with route property
|
|
208
|
+
* ```typescript
|
|
209
|
+
* const { data, isLoading } = useAPI({
|
|
210
|
+
* route: 'GET /users',
|
|
211
|
+
* query: { search: 'alice' }, // ✅ Use query params for GET
|
|
212
|
+
* // input: { ... }, // ❌ TypeScript error - GET cannot have input!
|
|
213
|
+
* staleTime: 5000,
|
|
214
|
+
* });
|
|
215
|
+
* ```
|
|
216
|
+
*
|
|
217
|
+
* @example GET request with method and path
|
|
218
|
+
* ```typescript
|
|
219
|
+
* const { data, isLoading } = useAPI({
|
|
220
|
+
* method: 'GET',
|
|
221
|
+
* path: '/users',
|
|
222
|
+
* query: { search: 'alice' },
|
|
223
|
+
* });
|
|
224
|
+
* ```
|
|
225
|
+
*
|
|
226
|
+
* @example POST request with manual invocation
|
|
227
|
+
* ```typescript
|
|
228
|
+
* const { invoke, data, isLoading } = useAPI('POST /users');
|
|
229
|
+
*
|
|
230
|
+
* // Invoke manually with input
|
|
231
|
+
* await invoke({ name: 'Alice', email: 'alice@example.com' }); // ✅ Fully typed!
|
|
232
|
+
* // data now contains the created user
|
|
233
|
+
* ```
|
|
234
|
+
*
|
|
235
|
+
* @example GET with query parameters
|
|
236
|
+
* ```typescript
|
|
237
|
+
* const { data } = useAPI({
|
|
238
|
+
* route: 'GET /search',
|
|
239
|
+
* query: { q: 'react', limit: '10' },
|
|
240
|
+
* });
|
|
241
|
+
* ```
|
|
242
|
+
*
|
|
243
|
+
* @example DELETE with no response body (204 No Content)
|
|
244
|
+
* ```typescript
|
|
245
|
+
* const { invoke, isSuccess } = useAPI('DELETE /users/:id');
|
|
246
|
+
*
|
|
247
|
+
* // Invoke when needed
|
|
248
|
+
* await invoke({ reason: 'Account closed' });
|
|
249
|
+
*
|
|
250
|
+
* // result.data doesn't exist! ❌ TypeScript error
|
|
251
|
+
* // Use isSuccess instead ✅
|
|
252
|
+
* if (isSuccess) {
|
|
253
|
+
* console.log('User deleted');
|
|
254
|
+
* }
|
|
255
|
+
* ```
|
|
256
|
+
*/
|
|
257
|
+
export function useAPI<TRoute extends RouteKey>(
|
|
258
|
+
routeOrOptions: TRoute | UseAPIOptions<TRoute>
|
|
259
|
+
): UseAPIResult<TRoute> {
|
|
260
|
+
// Normalize to options object
|
|
261
|
+
const options: UseAPIOptions<TRoute> =
|
|
262
|
+
typeof routeOrOptions === 'string'
|
|
263
|
+
? ({ route: routeOrOptions } as UseAPIOptions<TRoute>)
|
|
264
|
+
: routeOrOptions;
|
|
265
|
+
const context = useContext(AgentuityContext);
|
|
266
|
+
const {
|
|
267
|
+
input,
|
|
268
|
+
query,
|
|
269
|
+
headers,
|
|
270
|
+
enabled,
|
|
271
|
+
staleTime = 0,
|
|
272
|
+
refetchInterval,
|
|
273
|
+
onSuccess,
|
|
274
|
+
onError,
|
|
275
|
+
} = options;
|
|
276
|
+
|
|
277
|
+
if (!context) {
|
|
278
|
+
throw new Error('useAPI must be used within AgentuityProvider');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Extract method and path from either route OR {method, path}
|
|
282
|
+
let method: string;
|
|
283
|
+
let path: string;
|
|
284
|
+
|
|
285
|
+
if ('route' in options && options.route) {
|
|
286
|
+
const parsed = parseRouteKey(options.route as string);
|
|
287
|
+
method = parsed.method;
|
|
288
|
+
path = parsed.path;
|
|
289
|
+
} else if ('method' in options && 'path' in options && options.method && options.path) {
|
|
290
|
+
method = options.method;
|
|
291
|
+
path = options.path;
|
|
292
|
+
} else {
|
|
293
|
+
throw new Error('useAPI requires either route OR {method, path}');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const [data, setData] = useState<RouteOutput<TRoute> | undefined>(undefined);
|
|
297
|
+
const [error, setError] = useState<Error | null>(null);
|
|
298
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
299
|
+
const [isFetching, setIsFetching] = useState(false);
|
|
300
|
+
const [isSuccess, setIsSuccess] = useState(false);
|
|
301
|
+
const [isError, setIsError] = useState(false);
|
|
302
|
+
const lastFetchTimeRef = useRef<number>(0);
|
|
303
|
+
|
|
304
|
+
// Track mounted state to prevent state updates after unmount
|
|
305
|
+
const mountedRef = useRef(true);
|
|
306
|
+
useEffect(() => {
|
|
307
|
+
mountedRef.current = true;
|
|
308
|
+
return () => {
|
|
309
|
+
mountedRef.current = false;
|
|
310
|
+
};
|
|
311
|
+
}, []);
|
|
312
|
+
|
|
313
|
+
const fetchData = useCallback(async () => {
|
|
314
|
+
if (!mountedRef.current) return;
|
|
315
|
+
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
const lastFetchTime = lastFetchTimeRef.current;
|
|
318
|
+
|
|
319
|
+
// Check if data is still fresh based on last fetch time
|
|
320
|
+
const isFresh = staleTime > 0 && lastFetchTime !== 0 && now - lastFetchTime < staleTime;
|
|
321
|
+
if (isFresh) {
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
setIsFetching(true);
|
|
326
|
+
|
|
327
|
+
// isLoading = only for first load (or after reset)
|
|
328
|
+
if (lastFetchTime === 0) {
|
|
329
|
+
setIsLoading(true);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
setError(null);
|
|
333
|
+
setIsError(false);
|
|
334
|
+
|
|
335
|
+
try {
|
|
336
|
+
const url = buildUrl(context.baseUrl || '', path, undefined, toSearchParams(query));
|
|
337
|
+
const requestInit: RequestInit = {
|
|
338
|
+
method,
|
|
339
|
+
headers: {
|
|
340
|
+
'Content-Type': 'application/json',
|
|
341
|
+
...headers,
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
// Add body for non-GET requests
|
|
346
|
+
if (method !== 'GET' && input !== undefined) {
|
|
347
|
+
requestInit.body = JSON.stringify(input);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const response = await fetch(url, requestInit);
|
|
351
|
+
|
|
352
|
+
if (!response.ok) {
|
|
353
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
let responseData: any;
|
|
357
|
+
|
|
358
|
+
// Handle 204 No Content - no response body expected
|
|
359
|
+
if (response.status === 204) {
|
|
360
|
+
responseData = undefined;
|
|
361
|
+
} else {
|
|
362
|
+
const contentType = response.headers.get('Content-Type') || '';
|
|
363
|
+
if (contentType.includes('application/json')) {
|
|
364
|
+
responseData = await response.json();
|
|
365
|
+
} else {
|
|
366
|
+
const text = await response.text();
|
|
367
|
+
responseData = deserializeData<RouteOutput<TRoute>>(text);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (!mountedRef.current) return;
|
|
372
|
+
|
|
373
|
+
// Use JSON memoization to prevent re-renders when data hasn't changed
|
|
374
|
+
setData((prev) => {
|
|
375
|
+
const newData = responseData as RouteOutput<TRoute>;
|
|
376
|
+
if (prev !== undefined && JSON.stringify(prev) === JSON.stringify(newData)) {
|
|
377
|
+
return prev;
|
|
378
|
+
}
|
|
379
|
+
return newData;
|
|
380
|
+
});
|
|
381
|
+
setIsSuccess(true);
|
|
382
|
+
lastFetchTimeRef.current = Date.now();
|
|
383
|
+
|
|
384
|
+
onSuccess?.(responseData as RouteOutput<TRoute>);
|
|
385
|
+
} catch (err) {
|
|
386
|
+
if (!mountedRef.current) return;
|
|
387
|
+
|
|
388
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
389
|
+
setError(error);
|
|
390
|
+
setIsError(true);
|
|
391
|
+
onError?.(error);
|
|
392
|
+
} finally {
|
|
393
|
+
if (mountedRef.current) {
|
|
394
|
+
setIsLoading(false);
|
|
395
|
+
setIsFetching(false);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}, [context.baseUrl, path, method, input, query, headers, staleTime, onSuccess, onError]);
|
|
399
|
+
|
|
400
|
+
const reset = useCallback(() => {
|
|
401
|
+
setData(undefined);
|
|
402
|
+
setError(null);
|
|
403
|
+
setIsLoading(false);
|
|
404
|
+
setIsFetching(false);
|
|
405
|
+
setIsSuccess(false);
|
|
406
|
+
setIsError(false);
|
|
407
|
+
lastFetchTimeRef.current = 0;
|
|
408
|
+
}, []);
|
|
409
|
+
|
|
410
|
+
// For GET requests: auto-fetch and provide refetch
|
|
411
|
+
if (method === 'GET') {
|
|
412
|
+
const refetch = useCallback(async () => {
|
|
413
|
+
await fetchData();
|
|
414
|
+
}, [fetchData]);
|
|
415
|
+
|
|
416
|
+
// Auto-fetch on mount if enabled (default: true for GET)
|
|
417
|
+
const shouldAutoFetch = enabled ?? true;
|
|
418
|
+
useEffect(() => {
|
|
419
|
+
if (shouldAutoFetch) {
|
|
420
|
+
fetchData();
|
|
421
|
+
}
|
|
422
|
+
}, [shouldAutoFetch, fetchData]);
|
|
423
|
+
|
|
424
|
+
// Refetch interval
|
|
425
|
+
useEffect(() => {
|
|
426
|
+
if (!refetchInterval || refetchInterval <= 0) return;
|
|
427
|
+
|
|
428
|
+
const interval = setInterval(() => {
|
|
429
|
+
fetchData();
|
|
430
|
+
}, refetchInterval);
|
|
431
|
+
|
|
432
|
+
return () => clearInterval(interval);
|
|
433
|
+
}, [refetchInterval, fetchData]);
|
|
434
|
+
|
|
435
|
+
return {
|
|
436
|
+
data,
|
|
437
|
+
error,
|
|
438
|
+
isLoading,
|
|
439
|
+
isSuccess,
|
|
440
|
+
isError,
|
|
441
|
+
isFetching,
|
|
442
|
+
refetch,
|
|
443
|
+
reset,
|
|
444
|
+
} as unknown as UseAPIResult<TRoute>;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// For POST/PUT/PATCH/DELETE: provide invoke method (manual invocation)
|
|
448
|
+
const invoke = useCallback(
|
|
449
|
+
async (invokeInput?: RouteInput<TRoute>) => {
|
|
450
|
+
// Use invokeInput parameter if provided
|
|
451
|
+
const effectiveInput = invokeInput !== undefined ? invokeInput : input;
|
|
452
|
+
|
|
453
|
+
setIsFetching(true);
|
|
454
|
+
setIsLoading(true);
|
|
455
|
+
setError(null);
|
|
456
|
+
setIsError(false);
|
|
457
|
+
|
|
458
|
+
try {
|
|
459
|
+
const url = buildUrl(context.baseUrl || '', path, undefined, toSearchParams(query));
|
|
460
|
+
const requestInit: RequestInit = {
|
|
461
|
+
method,
|
|
462
|
+
headers: {
|
|
463
|
+
'Content-Type': 'application/json',
|
|
464
|
+
...headers,
|
|
465
|
+
},
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
if (effectiveInput !== undefined) {
|
|
469
|
+
requestInit.body = JSON.stringify(effectiveInput);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const response = await fetch(url, requestInit);
|
|
473
|
+
|
|
474
|
+
if (!response.ok) {
|
|
475
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
let responseData: any;
|
|
479
|
+
|
|
480
|
+
if (response.status === 204) {
|
|
481
|
+
responseData = undefined;
|
|
482
|
+
} else {
|
|
483
|
+
const contentType = response.headers.get('Content-Type') || '';
|
|
484
|
+
if (contentType.includes('application/json')) {
|
|
485
|
+
responseData = await response.json();
|
|
486
|
+
} else {
|
|
487
|
+
const text = await response.text();
|
|
488
|
+
responseData = deserializeData<RouteOutput<TRoute>>(text);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
if (!mountedRef.current) return responseData;
|
|
493
|
+
|
|
494
|
+
setData(responseData as RouteOutput<TRoute>);
|
|
495
|
+
setIsSuccess(true);
|
|
496
|
+
lastFetchTimeRef.current = Date.now();
|
|
497
|
+
|
|
498
|
+
onSuccess?.(responseData as RouteOutput<TRoute>);
|
|
499
|
+
|
|
500
|
+
return responseData as RouteOutput<TRoute>;
|
|
501
|
+
} catch (err) {
|
|
502
|
+
if (!mountedRef.current) throw err;
|
|
503
|
+
|
|
504
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
505
|
+
setError(error);
|
|
506
|
+
setIsError(true);
|
|
507
|
+
onError?.(error);
|
|
508
|
+
throw error;
|
|
509
|
+
} finally {
|
|
510
|
+
if (mountedRef.current) {
|
|
511
|
+
setIsLoading(false);
|
|
512
|
+
setIsFetching(false);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
[context.baseUrl, path, method, query, headers, input, onSuccess, onError]
|
|
517
|
+
);
|
|
518
|
+
|
|
519
|
+
return {
|
|
520
|
+
data,
|
|
521
|
+
error,
|
|
522
|
+
isLoading,
|
|
523
|
+
isSuccess,
|
|
524
|
+
isError,
|
|
525
|
+
isFetching,
|
|
526
|
+
invoke,
|
|
527
|
+
reset,
|
|
528
|
+
} as unknown as UseAPIResult<TRoute>;
|
|
529
|
+
}
|
package/src/env.ts
CHANGED