api-core-lib 12.12.111 → 16.2.0
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 +0 -1
- package/dist/index.d.mts +517 -0
- package/dist/index.d.ts +401 -109
- package/dist/index.js +1 -301
- package/dist/index.mjs +1 -0
- package/package.json +20 -51
- package/bin/cli-launcher.cjs +0 -14
- package/dist/apiModule.types-hGWAkTwf.d.cts +0 -299
- package/dist/apiModule.types-hGWAkTwf.d.ts +0 -299
- package/dist/chunk-JAMEOM7T.cjs +0 -384
- package/dist/chunk-N7HFSKII.js +0 -384
- package/dist/cli.cjs +0 -619
- package/dist/client.cjs +0 -535
- package/dist/client.d.cts +0 -50
- package/dist/client.d.ts +0 -50
- package/dist/client.js +0 -535
- package/dist/index.cjs +0 -301
- package/dist/index.d.cts +0 -225
- package/dist/server.cjs +0 -56
- package/dist/server.d.cts +0 -25
- package/dist/server.d.ts +0 -25
- package/dist/server.js +0 -56
- package/dist/useApiRecord.types-BJop2XPB.d.ts +0 -90
- package/dist/useApiRecord.types-V-4fiB7L.d.cts +0 -90
package/README.md
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"build": "tsup && node scripts/obfuscate.js",
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method } from 'axios';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @file src/types.ts
|
|
5
|
+
* @description This file serves as the central source for all data types and interfaces
|
|
6
|
+
* used throughout the library. Defining types here ensures consistency, type safety,
|
|
7
|
+
* and provides a clear API contract for the end-user.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Defines the structure for pagination metadata returned by the API.
|
|
12
|
+
*/
|
|
13
|
+
interface PaginationMeta {
|
|
14
|
+
itemsPerPage: number;
|
|
15
|
+
totalItems: number;
|
|
16
|
+
currentPage: number;
|
|
17
|
+
totalPages: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Represents the standard wrapper that an API might use for its responses.
|
|
21
|
+
* @template T The type of the core data payload.
|
|
22
|
+
*/
|
|
23
|
+
interface ApiResponse<T = any> {
|
|
24
|
+
success?: boolean;
|
|
25
|
+
data: T;
|
|
26
|
+
message?: string;
|
|
27
|
+
meta?: PaginationMeta;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Defines the structure for a single field validation error.
|
|
31
|
+
*/
|
|
32
|
+
interface ValidationError {
|
|
33
|
+
field: string;
|
|
34
|
+
message: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Represents the unified error object produced by the library for any failed request.
|
|
38
|
+
*/
|
|
39
|
+
interface ApiError {
|
|
40
|
+
message: string;
|
|
41
|
+
status: number;
|
|
42
|
+
code?: string;
|
|
43
|
+
errors?: ValidationError[];
|
|
44
|
+
requestId?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The standardized, final response object that every library function returns.
|
|
48
|
+
* This is the primary type developers will interact with.
|
|
49
|
+
* @template T The type of the final, unwrapped data.
|
|
50
|
+
*/
|
|
51
|
+
interface StandardResponse<T> {
|
|
52
|
+
data: T | null;
|
|
53
|
+
rawResponse: any;
|
|
54
|
+
error: ApiError | null;
|
|
55
|
+
loading: boolean;
|
|
56
|
+
success: boolean;
|
|
57
|
+
message?: string;
|
|
58
|
+
validationErrors?: ValidationError[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Represents the set of authentication tokens managed by the library.
|
|
62
|
+
*/
|
|
63
|
+
interface Tokens {
|
|
64
|
+
accessToken: string | null;
|
|
65
|
+
refreshToken: string | null;
|
|
66
|
+
expiresAt?: number;
|
|
67
|
+
tokenType?: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* An interface for a token manager, allowing the logic for token storage to be decoupled.
|
|
71
|
+
* Consumers of the library can provide their own implementation (e.g., LocalStorage, Cookies).
|
|
72
|
+
*/
|
|
73
|
+
interface TokenManager {
|
|
74
|
+
getTokens(): Promise<Tokens>;
|
|
75
|
+
setTokens(tokens: Tokens): Promise<void>;
|
|
76
|
+
clearTokens(): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Determines the operating context.
|
|
79
|
+
* @returns `true` if tokens are in secure httpOnly cookies (server-side context).
|
|
80
|
+
* @returns `false` if tokens are accessible from the client (e.g., localStorage).
|
|
81
|
+
*/
|
|
82
|
+
isHttpOnly(): boolean;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The context object passed to each middleware function in the pipeline.
|
|
86
|
+
*/
|
|
87
|
+
interface MiddlewareContext {
|
|
88
|
+
req: InternalAxiosRequestConfig;
|
|
89
|
+
res?: AxiosResponse;
|
|
90
|
+
error?: any;
|
|
91
|
+
custom?: Record<string, any>;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Defines the signature for a middleware function.
|
|
95
|
+
*/
|
|
96
|
+
type Middleware = (context: MiddlewareContext, next: () => Promise<void>) => Promise<void>;
|
|
97
|
+
/**
|
|
98
|
+
* Extends the default Axios request configuration with custom properties for the library.
|
|
99
|
+
*/
|
|
100
|
+
interface RequestConfig extends AxiosRequestConfig {
|
|
101
|
+
/** If true, the request will bypass the token injection logic. */
|
|
102
|
+
isPublic?: boolean;
|
|
103
|
+
/** A key for managing request cancellation. */
|
|
104
|
+
cancelTokenKey?: string;
|
|
105
|
+
/** Callback for upload progress events. */
|
|
106
|
+
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
|
107
|
+
/** Callback for download progress events. */
|
|
108
|
+
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Defines a flexible query options interface for pagination, sorting, filtering, and searching.
|
|
112
|
+
* Supports standard keys as well as any custom top-level query parameters.
|
|
113
|
+
* @example { page: 1, limit: 10, search: 'term', status: 'published' }
|
|
114
|
+
*/
|
|
115
|
+
interface QueryOptions {
|
|
116
|
+
page?: number;
|
|
117
|
+
limit?: number;
|
|
118
|
+
search?: string;
|
|
119
|
+
sortBy?: {
|
|
120
|
+
key: string;
|
|
121
|
+
direction: 'asc' | 'desc';
|
|
122
|
+
}[];
|
|
123
|
+
filter?: Record<string, any>;
|
|
124
|
+
[key: string]: any;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Defines additional options for action methods like create, update, or delete.
|
|
128
|
+
*/
|
|
129
|
+
interface ActionOptions extends RequestConfig {
|
|
130
|
+
/**
|
|
131
|
+
* Overrides the default endpoint for a specific action. Useful for specialized routes.
|
|
132
|
+
* @example update('123', { status: 'active' }, { endpoint: '/items/123/activate' })
|
|
133
|
+
*/
|
|
134
|
+
endpoint?: string;
|
|
135
|
+
/**
|
|
136
|
+
* Overrides the `refetchAfterChange` setting for a single action.
|
|
137
|
+
*/
|
|
138
|
+
refetch?: boolean;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The main configuration object for the `useApi` hook.
|
|
142
|
+
* @template T The data type the hook will manage.
|
|
143
|
+
*/
|
|
144
|
+
interface UseApiConfig<T> {
|
|
145
|
+
/** The base API endpoint for the resource (e.g., '/users'). */
|
|
146
|
+
endpoint: string;
|
|
147
|
+
/** Initial data to populate the state before the first fetch. */
|
|
148
|
+
initialData?: T | null;
|
|
149
|
+
/** Default query options to use for the initial fetch. */
|
|
150
|
+
initialQuery?: QueryOptions;
|
|
151
|
+
/** If false, the hook will not fetch data automatically on mount. */
|
|
152
|
+
enabled?: boolean;
|
|
153
|
+
/** If true, data will be refetched automatically after a successful create, update, or delete action. */
|
|
154
|
+
refetchAfterChange?: boolean;
|
|
155
|
+
/** A default `RequestConfig` to apply to all GET requests made by the hook. */
|
|
156
|
+
requestConfig?: RequestConfig;
|
|
157
|
+
encodeQuery?: boolean;
|
|
158
|
+
pathParams?: Record<string, string | number>;
|
|
159
|
+
/** Callback function executed on a successful action. */
|
|
160
|
+
onSuccess?: (message: string, data?: T) => void;
|
|
161
|
+
/** Callback function executed on a failed action. */
|
|
162
|
+
onError?: (message: string, error?: ApiError) => void;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Defines the configuration for the automatic token refresh mechanism.
|
|
166
|
+
*/
|
|
167
|
+
interface RefreshTokenConfig {
|
|
168
|
+
/** The API path for the token refresh endpoint (e.g., '/auth/refresh'). */
|
|
169
|
+
path: string;
|
|
170
|
+
/** A function to build the request body for the refresh call. */
|
|
171
|
+
buildRequestBody?: (refreshToken: string) => Record<string, any>;
|
|
172
|
+
/** A function to build any custom headers for the refresh call. */
|
|
173
|
+
buildRequestHeaders?: (currentTokens: Tokens) => Record<string, string>;
|
|
174
|
+
/**
|
|
175
|
+
* A function to extract the new tokens from the refresh API's response data.
|
|
176
|
+
* @param responseData The raw data from the refresh API response.
|
|
177
|
+
* @returns An object containing the new token details.
|
|
178
|
+
*/
|
|
179
|
+
extractTokens: (responseData: any) => {
|
|
180
|
+
accessToken: string;
|
|
181
|
+
refreshToken?: string;
|
|
182
|
+
expiresIn: number;
|
|
183
|
+
tokenType?: string;
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Defines the available levels for logging.
|
|
188
|
+
* 'debug': Logs everything.
|
|
189
|
+
* 'info': Logs standard requests and responses.
|
|
190
|
+
* 'warn': Logs warnings and errors.
|
|
191
|
+
* 'error': Logs only critical errors.
|
|
192
|
+
* 'silent': Disables all logging.
|
|
193
|
+
*/
|
|
194
|
+
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
195
|
+
/**
|
|
196
|
+
* An interface for a custom logger, compatible with the standard `console` object.
|
|
197
|
+
* It now includes a `debug` method for more granular logging.
|
|
198
|
+
*/
|
|
199
|
+
/**
|
|
200
|
+
* The main configuration object for the `createApiClient` factory function.
|
|
201
|
+
*/
|
|
202
|
+
interface ApiClientConfig {
|
|
203
|
+
/** The base URL for all API requests. */
|
|
204
|
+
baseURL?: string;
|
|
205
|
+
/** The token manager instance responsible for handling token storage. */
|
|
206
|
+
tokenManager: TokenManager;
|
|
207
|
+
/** The request timeout in milliseconds. */
|
|
208
|
+
timeout?: number;
|
|
209
|
+
/** Default headers to be sent with every request. */
|
|
210
|
+
headers?: Record<string, string>;
|
|
211
|
+
/** If true, cookies will be sent with cross-origin requests. */
|
|
212
|
+
withCredentials?: boolean;
|
|
213
|
+
/** Configuration for the automatic token refresh mechanism. */
|
|
214
|
+
refreshTokenConfig?: RefreshTokenConfig;
|
|
215
|
+
/** A callback function executed if the token refresh process fails. */
|
|
216
|
+
onRefreshError?: (error: any) => void;
|
|
217
|
+
/** A custom logger instance. Defaults to the browser `console`. */
|
|
218
|
+
/** An array of middleware functions to be executed with every request. */
|
|
219
|
+
middleware?: Middleware[];
|
|
220
|
+
/**
|
|
221
|
+
* Sets the verbosity of the internal logger.
|
|
222
|
+
* @default 'info'
|
|
223
|
+
*/
|
|
224
|
+
logLevel?: LogLevel;
|
|
225
|
+
/**
|
|
226
|
+
* If true, all requests will be treated as public by default.
|
|
227
|
+
* A request can override this by explicitly setting `isPublic: false`.
|
|
228
|
+
* @default false
|
|
229
|
+
*/
|
|
230
|
+
defaultIsPublic?: boolean;
|
|
231
|
+
maxTokenRefreshRetries?: number;
|
|
232
|
+
maxQueueSize?: number;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
declare function createApiClient(config: ApiClientConfig): AxiosInstance;
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* @file src/hooks/useApi.types.ts
|
|
239
|
+
* @description This file defines the professional, publicly-facing types for the `useApi` hook,
|
|
240
|
+
* providing a clean and stable contract for consumers.
|
|
241
|
+
*/
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Configuration object for the `useApi` hook.
|
|
245
|
+
* @template T The type of the data entity.
|
|
246
|
+
*/
|
|
247
|
+
/**
|
|
248
|
+
* The primary state object managed by the `useApi` hook.
|
|
249
|
+
* It contains the fetched data, loading status, and any potential errors.
|
|
250
|
+
* @template T The type of the data entity being managed.
|
|
251
|
+
*/
|
|
252
|
+
type UseApiState<T> = StandardResponse<T>;
|
|
253
|
+
/**
|
|
254
|
+
* A collection of callable functions for performing CRUD and other operations.
|
|
255
|
+
* These actions automatically handle state updates like loading and refetching.
|
|
256
|
+
* @template T The type of the data entity being managed.
|
|
257
|
+
*/
|
|
258
|
+
interface UseApiActions<T, TListItem = T extends (infer U)[] ? U : T> {
|
|
259
|
+
fetch: () => Promise<void>;
|
|
260
|
+
create: (newItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
|
|
261
|
+
put: (id: string | number, item: TListItem, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
|
|
262
|
+
update: (id: string | number, updatedItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
|
|
263
|
+
remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
264
|
+
bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* A collection of functions and properties for controlling the query parameters
|
|
268
|
+
* used for fetching data, such as pagination, sorting, and filtering.
|
|
269
|
+
*/
|
|
270
|
+
interface UseApiQuery {
|
|
271
|
+
/** The current query options state. */
|
|
272
|
+
options: QueryOptions;
|
|
273
|
+
/** A function to set the entire query options object at once. */
|
|
274
|
+
setOptions: React.Dispatch<React.SetStateAction<QueryOptions>>;
|
|
275
|
+
/** Sets the current page number. */
|
|
276
|
+
setPage: (page: number) => void;
|
|
277
|
+
/** Sets the number of items per page and resets to the first page. */
|
|
278
|
+
setLimit: (limit: number) => void;
|
|
279
|
+
/** Sets the search term and resets to the first page. */
|
|
280
|
+
setSearchTerm: (search: string) => void;
|
|
281
|
+
/** Sets the sorting configuration. */
|
|
282
|
+
setSorting: (sortBy: {
|
|
283
|
+
key: string;
|
|
284
|
+
direction: 'asc' | 'desc';
|
|
285
|
+
}[]) => void;
|
|
286
|
+
/** Sets the filter object and resets to the first page. */
|
|
287
|
+
setFilters: (filter: Record<string, any>) => void;
|
|
288
|
+
/** Sets a single, custom query parameter. */
|
|
289
|
+
setQueryParam: (key: string, value: any) => void;
|
|
290
|
+
/** Resets the query options to their initial state. */
|
|
291
|
+
reset: () => void;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The complete return type of the `useApi` hook.
|
|
295
|
+
* It encapsulates the state, actions, and query controls for a given API resource.
|
|
296
|
+
* @template T The type of the data entity being managed.
|
|
297
|
+
*/
|
|
298
|
+
interface UseApiReturn<T> {
|
|
299
|
+
state: UseApiState<T>;
|
|
300
|
+
setState: React.Dispatch<React.SetStateAction<UseApiState<T>>>;
|
|
301
|
+
actions: UseApiActions<T>;
|
|
302
|
+
query: UseApiQuery;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
interface ActionConfig<TInput = any, TOutput = any> {
|
|
306
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
307
|
+
path: string;
|
|
308
|
+
description?: string;
|
|
309
|
+
isList?: boolean;
|
|
310
|
+
invalidates?: string[];
|
|
311
|
+
autoFetch?: boolean;
|
|
312
|
+
upload?: boolean;
|
|
313
|
+
_input?: QueryOptions;
|
|
314
|
+
}
|
|
315
|
+
interface ApiModuleConfig {
|
|
316
|
+
baseEndpoint: string;
|
|
317
|
+
actions: Record<string, ActionConfig<any, any>>;
|
|
318
|
+
}
|
|
319
|
+
interface UrlSyncOptions<TModule extends ApiModuleConfig> {
|
|
320
|
+
searchParams: string;
|
|
321
|
+
updateUrl: (newSearchParams: string) => void;
|
|
322
|
+
actionsToSync: (keyof TModule['actions'])[];
|
|
323
|
+
defaultSyncAction?: keyof TModule['actions'];
|
|
324
|
+
}
|
|
325
|
+
interface UseApiModuleOptions<TModule extends ApiModuleConfig> {
|
|
326
|
+
onSuccess?: (actionName: string, message: string, data: any) => void;
|
|
327
|
+
onError?: (actionName: string, message: string, error?: ApiError | null) => void;
|
|
328
|
+
staleTime?: number;
|
|
329
|
+
cacheTime?: number;
|
|
330
|
+
refetchOnWindowFocus?: boolean;
|
|
331
|
+
dehydratedState?: Record<string, Partial<ActionState<any>>>;
|
|
332
|
+
urlSync?: UrlSyncOptions<TModule>;
|
|
333
|
+
initialActionsToExecute?: (keyof TModule['actions'])[];
|
|
334
|
+
defaultQueryOptions?: Partial<Record<keyof TModule['actions'], QueryOptions>>;
|
|
335
|
+
pathParams?: Record<string, any>;
|
|
336
|
+
}
|
|
337
|
+
interface ActionState<TOutput> {
|
|
338
|
+
data: TOutput | null;
|
|
339
|
+
error: ApiError | null;
|
|
340
|
+
loading: boolean;
|
|
341
|
+
success: boolean;
|
|
342
|
+
called: boolean;
|
|
343
|
+
}
|
|
344
|
+
interface ExecutableAction<TInput, TOutput> {
|
|
345
|
+
state: ActionState<TOutput>;
|
|
346
|
+
execute: (input?: TInput, options?: {
|
|
347
|
+
pathParams?: Record<string, any>;
|
|
348
|
+
config?: AxiosRequestConfig;
|
|
349
|
+
query?: QueryOptions;
|
|
350
|
+
onSuccess?: (message: string, data?: TOutput) => void;
|
|
351
|
+
onError?: (message: string, error?: ApiError | null) => void;
|
|
352
|
+
}) => Promise<StandardResponse<TOutput>>;
|
|
353
|
+
reset: () => void;
|
|
354
|
+
query?: UseApiQuery;
|
|
355
|
+
}
|
|
356
|
+
type ModuleActions<TModule extends ApiModuleConfig> = {
|
|
357
|
+
[K in keyof TModule['actions']]: TModule['actions'][K] extends ActionConfig<infer TInput, infer TOutput> ? ExecutableAction<TInput, TOutput> : never;
|
|
358
|
+
};
|
|
359
|
+
type ModuleStates<TModule extends ApiModuleConfig> = {
|
|
360
|
+
[K in keyof TModule['actions']]: TModule['actions'][K] extends ActionConfig<any, infer TOutput> ? ActionState<TOutput> : never;
|
|
361
|
+
};
|
|
362
|
+
type ModuleQueries<TModule extends ApiModuleConfig> = {
|
|
363
|
+
[K in keyof TModule['actions']]: TModule['actions'][K]['isList'] extends true ? UseApiQuery : undefined;
|
|
364
|
+
};
|
|
365
|
+
interface UseApiModuleReturn<TModule extends ApiModuleConfig> {
|
|
366
|
+
actions: {
|
|
367
|
+
[K in keyof TModule['actions']]: ModuleActions<TModule>[K]['execute'];
|
|
368
|
+
};
|
|
369
|
+
states: ModuleStates<TModule>;
|
|
370
|
+
queries: ModuleQueries<TModule>;
|
|
371
|
+
refetch: (actionName: keyof TModule['actions']) => Promise<StandardResponse<any> | undefined>;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* A factory function to create a reusable set of API services for a specific endpoint.
|
|
376
|
+
* It provides full CRUD operations plus advanced features like bulk deletion and file uploads,
|
|
377
|
+
* with intelligent, dynamic URL building.
|
|
378
|
+
*/
|
|
379
|
+
declare function createApiServices<T>(axiosInstance: AxiosInstance, baseEndpoint: string): {
|
|
380
|
+
get: (id?: string | number, config?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
381
|
+
getWithQuery: (query: string, config?: RequestConfig) => Promise<StandardResponse<T>>;
|
|
382
|
+
post: (data: Partial<T>, config?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
383
|
+
put: (id: string | number, data: T, config?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
384
|
+
patch: (id: string | number, data: Partial<T>, config?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
385
|
+
remove: (id: string | number, config?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
386
|
+
bulkDelete: (ids: Array<string | number>, config?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
387
|
+
upload: (file: File, additionalData?: Record<string, any>, config?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* @file src/core/utils.ts
|
|
392
|
+
* @description
|
|
393
|
+
* يحتوي هذا الملف على مجموعة من الدوال المساعدة المستخدمة في جميع أنحاء المكتبة،
|
|
394
|
+
* مثل بناء سلاسل الاستعلام (query strings) وإدارة إلغاء الطلبات،
|
|
395
|
+
* بالإضافة إلى دوال التحقق من الأنواع (type guards).
|
|
396
|
+
*/
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* يبني سلسلة استعلام (query string) من كائن خيارات مرن.
|
|
400
|
+
* يتعامل مع البارامترات القياسية والمخصصة.
|
|
401
|
+
* @param query - كائن من نوع QueryOptions.
|
|
402
|
+
* @returns سلسلة استعلام جاهزة للإضافة للرابط.
|
|
403
|
+
*/
|
|
404
|
+
declare function buildPaginateQuery(query: QueryOptions): string;
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Defines a single custom API action.
|
|
408
|
+
* @template TRequest - The type of the data sent in the request body/params.
|
|
409
|
+
* @template TResponse - The type of the data expected in the successful API response.
|
|
410
|
+
*/
|
|
411
|
+
type ApiAction<TRequest, TResponse> = (payload: TRequest, config?: RequestConfig) => Promise<StandardResponse<TResponse>>;
|
|
412
|
+
/**
|
|
413
|
+
* A factory function to create a collection of typed, custom API actions.
|
|
414
|
+
*
|
|
415
|
+
* @template TActions - An object type where keys are action names and values are objects
|
|
416
|
+
* defining the endpoint, method, and types for that action.
|
|
417
|
+
* @param axiosInstance - The configured Axios instance from `createApiClient`.
|
|
418
|
+
* @param actionsConfig - An object defining the configuration for each custom action.
|
|
419
|
+
* @returns A fully-typed object of executable API action functions.
|
|
420
|
+
*
|
|
421
|
+
* @example
|
|
422
|
+
* const authActions = createApiActions(apiClient, {
|
|
423
|
+
* login: { method: 'POST', endpoint: '/auth/login', requestType: {} as LoginCredentials, responseType: {} as AuthResponse },
|
|
424
|
+
* getProfile: { method: 'GET', endpoint: '/user/profile', requestType: {} as void, responseType: {} as UserProfile }
|
|
425
|
+
* });
|
|
426
|
+
*
|
|
427
|
+
* // Usage:
|
|
428
|
+
* const result = await authActions.login({ email: '..', password: '..' });
|
|
429
|
+
*/
|
|
430
|
+
declare function createApiActions<TActions extends Record<string, {
|
|
431
|
+
method: Method;
|
|
432
|
+
endpoint: string;
|
|
433
|
+
requestType: any;
|
|
434
|
+
responseType: any;
|
|
435
|
+
log?: boolean;
|
|
436
|
+
}>>(axiosInstance: AxiosInstance, actionsConfig: TActions): {
|
|
437
|
+
[K in keyof TActions]: ApiAction<TActions[K]['requestType'], TActions[K]['responseType']>;
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
interface CacheItem<T> {
|
|
441
|
+
data: T;
|
|
442
|
+
timestamp: number;
|
|
443
|
+
duration: number;
|
|
444
|
+
}
|
|
445
|
+
declare class CacheManager {
|
|
446
|
+
private cache;
|
|
447
|
+
private defaultDuration;
|
|
448
|
+
set<T>(key: string, data: T, duration?: number): void;
|
|
449
|
+
get<T>(key: string): T | null;
|
|
450
|
+
/**
|
|
451
|
+
* [دالة جديدة] تعيد عنصر الـ Cache بالكامل (البيانات + معلومات إضافية)
|
|
452
|
+
* دون حذفه عند انتهاء الصلاحية. هذا يسمح لنا بتطبيق منطق stale-while-revalidate.
|
|
453
|
+
*/
|
|
454
|
+
getWithMeta<T>(key: string): CacheItem<T> | null;
|
|
455
|
+
delete(key: string): void;
|
|
456
|
+
clear(): void;
|
|
457
|
+
/**
|
|
458
|
+
* [دالة جديدة] تقوم بإبطال (حذف) جميع عناصر الـ Cache التي تبدأ ببادئة معينة.
|
|
459
|
+
* أساسية لعملية invalidation التلقائية.
|
|
460
|
+
*/
|
|
461
|
+
invalidateByPrefix(prefix: string): void;
|
|
462
|
+
}
|
|
463
|
+
declare const cacheManager: CacheManager;
|
|
464
|
+
|
|
465
|
+
declare const processResponse: <T>(responseOrError: AxiosResponse<any> | ApiError) => StandardResponse<T>;
|
|
466
|
+
|
|
467
|
+
declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
|
|
468
|
+
|
|
469
|
+
declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions<TModule>): UseApiModuleReturn<TModule>;
|
|
470
|
+
|
|
471
|
+
type ApiResourceStatus = 'idle' | 'loading' | 'success' | 'error';
|
|
472
|
+
interface UseApiResourceState<T> {
|
|
473
|
+
data: T | T[] | null;
|
|
474
|
+
error: ApiError | null;
|
|
475
|
+
status: ApiResourceStatus;
|
|
476
|
+
isFetching: boolean;
|
|
477
|
+
isMutating: boolean;
|
|
478
|
+
isSuccess: boolean;
|
|
479
|
+
lastResponse?: StandardResponse<any>;
|
|
480
|
+
}
|
|
481
|
+
interface UseApiResourceActions<T, TCreate, TUpdate, TPathParams> {
|
|
482
|
+
fetch: (pathParams?: TPathParams, queryOptions?: QueryOptions) => Promise<StandardResponse<T[]>>;
|
|
483
|
+
fetchOne: (pathParams: TPathParams & {
|
|
484
|
+
id: string | number;
|
|
485
|
+
}, queryOptions?: QueryOptions) => Promise<StandardResponse<T>>;
|
|
486
|
+
create: (newItem: TCreate, pathParams?: TPathParams, options?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
487
|
+
update: (id: string | number, updatedItem: TUpdate, pathParams?: TPathParams, options?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
488
|
+
remove: (id: string | number, pathParams?: TPathParams, options?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
489
|
+
reset: () => void;
|
|
490
|
+
}
|
|
491
|
+
interface UseApiResourceConfig<TPathParams> {
|
|
492
|
+
/**
|
|
493
|
+
* The API endpoint template. Can be a static string or a function
|
|
494
|
+
* that builds the URL from parameters.
|
|
495
|
+
* @example '/users'
|
|
496
|
+
* @example (params) => `/modules/${params.moduleName}/records`
|
|
497
|
+
*/
|
|
498
|
+
endpoint: string | ((params: TPathParams) => string);
|
|
499
|
+
/** Initial data to populate the state. */
|
|
500
|
+
initialData?: any;
|
|
501
|
+
/** Controls the verbosity of console logs for debugging. */
|
|
502
|
+
logLevel?: LogLevel;
|
|
503
|
+
/** Unique identifier for this hook instance, used in logging. */
|
|
504
|
+
logKey?: string;
|
|
505
|
+
/** Callback for success */
|
|
506
|
+
onSuccess?: (message: string, data?: any) => void;
|
|
507
|
+
/** Callback for error */
|
|
508
|
+
onError?: (message: string, error?: ApiError) => void;
|
|
509
|
+
}
|
|
510
|
+
interface UseApiResourceReturn<T, TCreate, TUpdate, TPathParams> {
|
|
511
|
+
state: UseApiResourceState<T>;
|
|
512
|
+
actions: UseApiResourceActions<T, TCreate, TUpdate, TPathParams>;
|
|
513
|
+
query: UseApiQuery;
|
|
514
|
+
setQuery: React.Dispatch<React.SetStateAction<QueryOptions>>;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type ModuleQueries, type ModuleStates, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UrlSyncOptions, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiModuleReturn, type UseApiQuery, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule };
|