api-core-lib 11.11.10 → 12.0.4
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/index.d.mts +340 -254
- package/dist/index.d.ts +340 -254
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,40 +1,26 @@
|
|
|
1
|
-
import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method } from 'axios';
|
|
1
|
+
import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method, AxiosError } from 'axios';
|
|
2
|
+
import * as React$1 from 'react';
|
|
3
|
+
import React__default, { Dispatch, SetStateAction } from 'react';
|
|
2
4
|
|
|
3
5
|
/**
|
|
4
|
-
*
|
|
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.
|
|
6
|
+
* يمثل معلومات الترقيم (Pagination) التي قد تعود من ה-API.
|
|
12
7
|
*/
|
|
13
8
|
interface PaginationMeta {
|
|
14
9
|
itemsPerPage: number;
|
|
15
10
|
totalItems: number;
|
|
16
11
|
currentPage: number;
|
|
17
12
|
totalPages: number;
|
|
13
|
+
[key: string]: any;
|
|
18
14
|
}
|
|
19
15
|
/**
|
|
20
|
-
*
|
|
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.
|
|
16
|
+
* يمثل خطأ تحقق واحد لحقل معين.
|
|
31
17
|
*/
|
|
32
18
|
interface ValidationError {
|
|
33
19
|
field: string;
|
|
34
20
|
message: string;
|
|
35
21
|
}
|
|
36
22
|
/**
|
|
37
|
-
*
|
|
23
|
+
* يمثل كائن الخطأ الموحد الذي تنتجه المكتبة.
|
|
38
24
|
*/
|
|
39
25
|
interface ApiError {
|
|
40
26
|
message: string;
|
|
@@ -44,12 +30,14 @@ interface ApiError {
|
|
|
44
30
|
requestId?: string;
|
|
45
31
|
}
|
|
46
32
|
/**
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* @template T
|
|
33
|
+
* الكائن القياسي والموحد الذي تعيده جميع دوال المكتبة.
|
|
34
|
+
* هذا هو النوع الأساسي الذي سيتعامل معه المطورون.
|
|
35
|
+
* @template T نوع البيانات الأساسية.
|
|
50
36
|
*/
|
|
51
37
|
interface StandardResponse<T> {
|
|
52
38
|
data: T | null;
|
|
39
|
+
links?: Record<string, string | null>;
|
|
40
|
+
meta?: PaginationMeta | Record<string, any>;
|
|
53
41
|
rawResponse: any;
|
|
54
42
|
error: ApiError | null;
|
|
55
43
|
loading: boolean;
|
|
@@ -57,125 +45,30 @@ interface StandardResponse<T> {
|
|
|
57
45
|
message?: string;
|
|
58
46
|
validationErrors?: ValidationError[];
|
|
59
47
|
}
|
|
60
|
-
/**
|
|
61
|
-
* Represents the set of authentication tokens managed by the library.
|
|
62
|
-
*/
|
|
63
48
|
interface Tokens {
|
|
64
49
|
accessToken: string | null;
|
|
65
50
|
refreshToken: string | null;
|
|
66
51
|
expiresAt?: number;
|
|
67
52
|
tokenType?: string;
|
|
68
53
|
}
|
|
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
54
|
interface TokenManager {
|
|
74
55
|
getTokens(): Promise<Tokens>;
|
|
75
56
|
setTokens(tokens: Tokens): Promise<void>;
|
|
76
57
|
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
58
|
isHttpOnly(): boolean;
|
|
83
59
|
}
|
|
84
|
-
/**
|
|
85
|
-
* The context object passed to each middleware function in the pipeline.
|
|
86
|
-
*/
|
|
87
60
|
interface MiddlewareContext {
|
|
88
61
|
req: InternalAxiosRequestConfig;
|
|
89
62
|
res?: AxiosResponse;
|
|
90
63
|
error?: any;
|
|
91
64
|
custom?: Record<string, any>;
|
|
92
65
|
}
|
|
93
|
-
/**
|
|
94
|
-
* Defines the signature for a middleware function.
|
|
95
|
-
*/
|
|
96
66
|
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
|
-
*/
|
|
67
|
+
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
167
68
|
interface RefreshTokenConfig {
|
|
168
|
-
/** The API path for the token refresh endpoint (e.g., '/auth/refresh'). */
|
|
169
69
|
path: string;
|
|
170
|
-
/** A function to build the request body for the refresh call. */
|
|
171
70
|
buildRequestBody?: (refreshToken: string) => Record<string, any>;
|
|
172
|
-
/** A function to build any custom headers for the refresh call. */
|
|
173
71
|
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
72
|
extractTokens: (responseData: any) => {
|
|
180
73
|
accessToken: string;
|
|
181
74
|
refreshToken?: string;
|
|
@@ -183,95 +76,88 @@ interface RefreshTokenConfig {
|
|
|
183
76
|
tokenType?: string;
|
|
184
77
|
};
|
|
185
78
|
}
|
|
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
79
|
interface ApiClientConfig {
|
|
203
|
-
/** The base URL for all API requests. */
|
|
204
80
|
baseURL?: string;
|
|
205
|
-
/** The token manager instance responsible for handling token storage. */
|
|
206
81
|
tokenManager: TokenManager;
|
|
207
|
-
/** The request timeout in milliseconds. */
|
|
208
82
|
timeout?: number;
|
|
209
|
-
/** Default headers to be sent with every request. */
|
|
210
83
|
headers?: Record<string, string>;
|
|
211
|
-
/** If true, cookies will be sent with cross-origin requests. */
|
|
212
84
|
withCredentials?: boolean;
|
|
213
|
-
/** Configuration for the automatic token refresh mechanism. */
|
|
214
85
|
refreshTokenConfig?: RefreshTokenConfig;
|
|
215
|
-
/** A callback function executed if the token refresh process fails. */
|
|
216
86
|
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
87
|
middleware?: Middleware[];
|
|
220
|
-
/**
|
|
221
|
-
* Sets the verbosity of the internal logger.
|
|
222
|
-
* @default 'info'
|
|
223
|
-
*/
|
|
224
88
|
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
89
|
defaultIsPublic?: boolean;
|
|
231
90
|
maxTokenRefreshRetries?: number;
|
|
232
91
|
maxQueueSize?: number;
|
|
233
92
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
93
|
+
interface RequestConfig extends AxiosRequestConfig {
|
|
94
|
+
isPublic?: boolean;
|
|
95
|
+
cancelTokenKey?: string;
|
|
96
|
+
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
|
97
|
+
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
|
98
|
+
}
|
|
99
|
+
interface QueryOptions {
|
|
100
|
+
page?: number;
|
|
101
|
+
limit?: number;
|
|
102
|
+
search?: string;
|
|
103
|
+
sortBy?: {
|
|
104
|
+
key: string;
|
|
105
|
+
direction: 'asc' | 'desc';
|
|
106
|
+
}[];
|
|
107
|
+
filter?: Record<string, any>;
|
|
108
|
+
[key: string]: any;
|
|
109
|
+
}
|
|
110
|
+
interface ActionOptions extends RequestConfig {
|
|
111
|
+
endpoint?: string;
|
|
112
|
+
refetch?: boolean;
|
|
113
|
+
}
|
|
247
114
|
/**
|
|
248
|
-
*
|
|
249
|
-
* It contains the fetched data, loading status, and any potential errors.
|
|
250
|
-
* @template T The type of the data entity being managed.
|
|
115
|
+
* يمثل إعدادات إجراء واحد داخل الموديول.
|
|
251
116
|
*/
|
|
252
|
-
|
|
117
|
+
interface ActionConfig<TInput = any, TOutput = any> {
|
|
118
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
119
|
+
path: string;
|
|
120
|
+
description?: string;
|
|
121
|
+
isList?: boolean;
|
|
122
|
+
invalidates?: string[];
|
|
123
|
+
}
|
|
253
124
|
/**
|
|
254
|
-
*
|
|
255
|
-
*
|
|
256
|
-
* @template T The type of the data entity being managed.
|
|
125
|
+
* [مُحدَّث] يمثل الحالة التفاعلية الكاملة لإجراء واحد.
|
|
126
|
+
* هذا هو النوع الذي يتم إرجاعه في `states` من الهوك.
|
|
257
127
|
*/
|
|
258
|
-
interface
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
128
|
+
interface ActionStateModule<TOutput> {
|
|
129
|
+
data: TOutput | null;
|
|
130
|
+
links?: Record<string, string | null>;
|
|
131
|
+
meta?: PaginationMeta | Record<string, any>;
|
|
132
|
+
error: ApiError | null;
|
|
133
|
+
loading: boolean;
|
|
134
|
+
success: boolean;
|
|
135
|
+
called: boolean;
|
|
136
|
+
message?: string;
|
|
137
|
+
validationErrors?: ValidationError[];
|
|
138
|
+
rawResponse: any | null;
|
|
139
|
+
isStale?: boolean;
|
|
140
|
+
lastSuccessAt?: number;
|
|
265
141
|
}
|
|
266
142
|
/**
|
|
267
|
-
*
|
|
268
|
-
* used for fetching data, such as pagination, sorting, and filtering.
|
|
143
|
+
* الكائن الموحد الذي يتم إرجاعه لكل إجراء، ويحتوي على حالته ومنفذه وأدوات التحكم.
|
|
269
144
|
*/
|
|
145
|
+
interface ExecutableAction<TInput, TOutput> {
|
|
146
|
+
state: ActionStateModule<TOutput>;
|
|
147
|
+
execute: (input?: TInput, options?: {
|
|
148
|
+
pathParams?: Record<string, any>;
|
|
149
|
+
config?: AxiosRequestConfig;
|
|
150
|
+
query?: QueryOptions;
|
|
151
|
+
}) => Promise<StandardResponse<TOutput>>;
|
|
152
|
+
reset: () => void;
|
|
153
|
+
query?: UseApiQuery;
|
|
154
|
+
}
|
|
155
|
+
type UseApiState<T> = StandardResponse<T>;
|
|
270
156
|
interface UseApiQuery {
|
|
271
157
|
/** The current query options state. */
|
|
272
158
|
options: QueryOptions;
|
|
273
159
|
/** A function to set the entire query options object at once. */
|
|
274
|
-
setOptions:
|
|
160
|
+
setOptions: React__default.Dispatch<React__default.SetStateAction<QueryOptions>>;
|
|
275
161
|
/** Sets the current page number. */
|
|
276
162
|
setPage: (page: number) => void;
|
|
277
163
|
/** Sets the number of items per page and resets to the first page. */
|
|
@@ -290,68 +176,86 @@ interface UseApiQuery {
|
|
|
290
176
|
/** Resets the query options to their initial state. */
|
|
291
177
|
reset: () => void;
|
|
292
178
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
179
|
+
interface UseApiConfig<T> {
|
|
180
|
+
endpoint: string;
|
|
181
|
+
initialData?: T | null;
|
|
182
|
+
initialQuery?: QueryOptions;
|
|
183
|
+
enabled?: boolean;
|
|
184
|
+
refetchAfterChange?: boolean;
|
|
185
|
+
requestConfig?: RequestConfig;
|
|
186
|
+
pathParams?: Record<string, string | number>;
|
|
187
|
+
encodeQuery?: boolean;
|
|
188
|
+
onSuccess?: (message: string, data?: T) => void;
|
|
189
|
+
onError?: (message: string, error?: ApiError) => void;
|
|
303
190
|
}
|
|
304
191
|
|
|
305
|
-
|
|
192
|
+
declare function createApiClient(config: ApiClientConfig): AxiosInstance;
|
|
193
|
+
|
|
194
|
+
/** @description Extends the base ActionState with an `isStale` flag for automatic refetching. */
|
|
195
|
+
interface ActionState<TOutput> extends ActionStateModule<TOutput> {
|
|
196
|
+
isStale?: boolean;
|
|
197
|
+
}
|
|
198
|
+
/** @description Defines the configuration for a single API action within a module. */
|
|
199
|
+
interface ActionConfigModule<TInput = unknown, TOutput = unknown> {
|
|
306
200
|
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
307
201
|
path: string;
|
|
308
202
|
description?: string;
|
|
309
|
-
|
|
203
|
+
hasQuery?: boolean;
|
|
204
|
+
autoFetch?: boolean;
|
|
310
205
|
invalidates?: string[];
|
|
206
|
+
_input?: TInput;
|
|
207
|
+
_output?: TOutput;
|
|
311
208
|
}
|
|
312
|
-
|
|
209
|
+
/** @description Defines the complete structure of an API module. */
|
|
210
|
+
interface ApiModuleConfig<TActions extends Record<string, ActionConfigModule<any, any>>> {
|
|
313
211
|
baseEndpoint: string;
|
|
314
|
-
actions:
|
|
212
|
+
actions: TActions;
|
|
315
213
|
}
|
|
214
|
+
/** @description Configuration options passed directly to the `useApiModule` hook. */
|
|
316
215
|
interface UseApiModuleOptions {
|
|
317
|
-
onSuccess?: (actionName: string, message: string, data:
|
|
216
|
+
onSuccess?: (actionName: string, message: string, data: unknown) => void;
|
|
318
217
|
onError?: (actionName: string, message: string, error?: ApiError | null) => void;
|
|
319
|
-
staleTime?: number;
|
|
320
|
-
cacheTime?: number;
|
|
321
218
|
refetchOnWindowFocus?: boolean;
|
|
219
|
+
pathParams?: Record<string, any>;
|
|
220
|
+
enabled?: boolean;
|
|
221
|
+
hydratedState?: string;
|
|
322
222
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
interface ExecutableAction<TInput, TOutput> {
|
|
335
|
-
/** The reactive state for this specific action. */
|
|
336
|
-
state: ActionState<TOutput>;
|
|
337
|
-
/** The stable function to execute the API call. */
|
|
338
|
-
execute: (input?: TInput, options?: {
|
|
339
|
-
pathParams?: Record<string, any>;
|
|
340
|
-
config?: AxiosRequestConfig;
|
|
341
|
-
query?: QueryOptions;
|
|
342
|
-
}) => Promise<StandardResponse<TOutput>>;
|
|
343
|
-
/** A stable function to reset the action's state to its initial value. */
|
|
344
|
-
reset: () => void;
|
|
345
|
-
/** Query controls (pagination, sorting, etc.) available only if `isList: true`. */
|
|
346
|
-
query?: UseApiQuery;
|
|
223
|
+
/** A utility type to infer the Input type (`TInput`) from an ActionConfigModule. */
|
|
224
|
+
type InputOf<TActionConfig> = TActionConfig extends ActionConfigModule<infer TInput, any> ? TInput : never;
|
|
225
|
+
/** A utility type to infer the Output type (`TOutput`) from an ActionConfigModule. */
|
|
226
|
+
type OutputOf<TActionConfig> = TActionConfig extends ActionConfigModule<any, infer TOutput> ? TOutput : never;
|
|
227
|
+
/** @description Defines the options for the `execute` function, enabling optimistic updates. */
|
|
228
|
+
interface ExecuteOptions<TInput, TOutput, TContext = unknown> {
|
|
229
|
+
pathParams?: Record<string, any>;
|
|
230
|
+
config?: AxiosRequestConfig;
|
|
231
|
+
onMutate?: (variables: TInput) => TContext | Promise<TContext>;
|
|
232
|
+
onSuccess?: (data: TOutput, context?: TContext) => void;
|
|
233
|
+
onError?: (error: ApiError, context?: TContext) => void;
|
|
347
234
|
}
|
|
348
|
-
/**
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
235
|
+
/** @description A fully-typed object representing the callable actions for a module. */
|
|
236
|
+
type ModuleActions<TActions extends Record<string, ActionConfigModule<any, any>>> = {
|
|
237
|
+
[K in keyof TActions]: {
|
|
238
|
+
execute: <TContext = unknown>(input?: InputOf<TActions[K]>, options?: ExecuteOptions<InputOf<TActions[K]>, OutputOf<TActions[K]>, TContext>) => Promise<StandardResponse<OutputOf<TActions[K]>>>;
|
|
239
|
+
reset: (input?: InputOf<TActions[K]>, options?: {
|
|
240
|
+
pathParams?: Record<string, any>;
|
|
241
|
+
}) => void;
|
|
242
|
+
};
|
|
243
|
+
};
|
|
244
|
+
/** @description A fully-typed object representing the reactive states for each action in a module. */
|
|
245
|
+
type ModuleStates<TActions extends Record<string, ActionConfigModule<any, any>>> = {
|
|
246
|
+
[K in keyof TActions]: ActionState<OutputOf<TActions[K]>>;
|
|
354
247
|
};
|
|
248
|
+
/** @description The complete, fully-typed return object of the `useApiModule` hook. */
|
|
249
|
+
interface UseApiModuleReturn<TActions extends Record<string, ActionConfigModule<any, any>>> {
|
|
250
|
+
states: ModuleStates<TActions>;
|
|
251
|
+
actions: ModuleActions<TActions>;
|
|
252
|
+
queries: {
|
|
253
|
+
[K in keyof TActions]?: TActions[K] extends {
|
|
254
|
+
hasQuery: true;
|
|
255
|
+
} ? UseApiQuery : never;
|
|
256
|
+
};
|
|
257
|
+
dehydrate: () => string;
|
|
258
|
+
}
|
|
355
259
|
|
|
356
260
|
/**
|
|
357
261
|
* A factory function to create a reusable set of API services for a specific endpoint.
|
|
@@ -368,22 +272,30 @@ declare function createApiServices<T>(axiosInstance: AxiosInstance, baseEndpoint
|
|
|
368
272
|
bulkDelete: (ids: Array<string | number>, config?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
369
273
|
upload: (file: File, additionalData?: Record<string, any>, config?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
370
274
|
};
|
|
371
|
-
|
|
372
275
|
/**
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
*
|
|
377
|
-
*
|
|
276
|
+
* [نسخة محدثة ومحسّنة]
|
|
277
|
+
* دالة عامة وصريحة لتنفيذ أي طلب API.
|
|
278
|
+
* تستقبل وسائط منظمة بدلاً من محاولة تخمينها.
|
|
279
|
+
*
|
|
280
|
+
* @param axiosInstance - نسخة Axios.
|
|
281
|
+
* @param baseEndpoint - نقطة النهاية الأساسية للموديول.
|
|
282
|
+
* @param actionConfig - إعدادات الإجراء المحدد.
|
|
283
|
+
* @param params - كائن يحتوي على جميع البارامترات اللازمة للطلب.
|
|
284
|
+
* @returns Promise<StandardResponse<any>>
|
|
378
285
|
*/
|
|
286
|
+
declare function callDynamicApi(axiosInstance: AxiosInstance, baseEndpoint: string, actionConfig: ActionConfigModule<any, any>, params: {
|
|
287
|
+
pathParams?: Record<string, string | number>;
|
|
288
|
+
body?: any;
|
|
289
|
+
config?: AxiosRequestConfig;
|
|
290
|
+
}): Promise<StandardResponse<any>>;
|
|
379
291
|
|
|
380
292
|
/**
|
|
381
|
-
* يبني سلسلة استعلام (query string) من كائن
|
|
382
|
-
*
|
|
383
|
-
* @param
|
|
293
|
+
* [نسخة مطورة] يبني سلسلة استعلام (query string) من كائن الخيارات.
|
|
294
|
+
* يدعم الآن الفلاتر المتداخلة (filter[key]=value) والترتيب المتعدد.
|
|
295
|
+
* @param options - كائن خيارات الاستعلام (فلترة, ترتيب, ...).
|
|
384
296
|
* @returns سلسلة استعلام جاهزة للإضافة للرابط.
|
|
385
297
|
*/
|
|
386
|
-
declare function buildPaginateQuery(
|
|
298
|
+
declare function buildPaginateQuery(options: QueryOptions): string;
|
|
387
299
|
|
|
388
300
|
/**
|
|
389
301
|
* Defines a single custom API action.
|
|
@@ -430,30 +342,204 @@ declare class CacheManager {
|
|
|
430
342
|
set<T>(key: string, data: T, duration?: number): void;
|
|
431
343
|
get<T>(key: string): T | null;
|
|
432
344
|
/**
|
|
433
|
-
* [
|
|
434
|
-
*
|
|
345
|
+
* [FIX] تم تحويلها إلى دالة عامة (generic) لتعيد النوع الصحيح.
|
|
346
|
+
* الآن بدلًا من إرجاع CacheItem<unknown>، ستُرجع CacheItem<T>.
|
|
435
347
|
*/
|
|
436
348
|
getWithMeta<T>(key: string): CacheItem<T> | null;
|
|
437
349
|
delete(key: string): void;
|
|
438
350
|
clear(): void;
|
|
439
|
-
/**
|
|
440
|
-
* [دالة جديدة] تقوم بإبطال (حذف) جميع عناصر الـ Cache التي تبدأ ببادئة معينة.
|
|
441
|
-
* أساسية لعملية invalidation التلقائية.
|
|
442
|
-
*/
|
|
443
351
|
invalidateByPrefix(prefix: string): void;
|
|
444
352
|
}
|
|
445
353
|
declare const cacheManager: CacheManager;
|
|
446
354
|
|
|
447
|
-
|
|
355
|
+
/**
|
|
356
|
+
* [النسخة النهائية والمضمونة]
|
|
357
|
+
* تستخدم دوال حماية النوع المخصصة للقضاء على أخطاء 'never' بشكل نهائي.
|
|
358
|
+
*/
|
|
359
|
+
declare const processResponse: <T>(responseOrError: AxiosResponse<any> | AxiosError) => StandardResponse<T>;
|
|
360
|
+
|
|
361
|
+
declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): any;
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Represents the internal state of the `useApiRecord` hook.
|
|
365
|
+
* It mirrors the `StandardResponse` structure, which is the unified response format
|
|
366
|
+
* used across the library.
|
|
367
|
+
* @template T The data type of the record.
|
|
368
|
+
*/
|
|
369
|
+
type UseApiRecordState<T> = StandardResponse<T>;
|
|
370
|
+
/**
|
|
371
|
+
* Defines the action methods provided by the `useApiRecord` hook to interact with
|
|
372
|
+
* a single API resource.
|
|
373
|
+
* @template T The data type of the record.
|
|
374
|
+
*/
|
|
375
|
+
interface UseApiRecordActions<T> {
|
|
376
|
+
/**
|
|
377
|
+
* Manually fetches or refetches the record from the API.
|
|
378
|
+
*/
|
|
379
|
+
fetch: () => Promise<void>;
|
|
380
|
+
/**
|
|
381
|
+
* Partially updates the record using an HTTP PATCH request.
|
|
382
|
+
* @param updatedItem An object containing the fields to update.
|
|
383
|
+
* @param options Additional request options, allowing overrides for this specific action.
|
|
384
|
+
* @returns A promise that resolves to the standard response object for the updated record.
|
|
385
|
+
*/
|
|
386
|
+
update: (updatedItem: Partial<T>, options?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
387
|
+
/**
|
|
388
|
+
* Replaces the entire record with a new one using an HTTP PUT request.
|
|
389
|
+
* @param item The complete new record object.
|
|
390
|
+
* @param options Additional request options.
|
|
391
|
+
* @returns A promise that resolves to the standard response object for the replaced record.
|
|
392
|
+
*/
|
|
393
|
+
put: (item: T, options?: ActionOptions) => Promise<StandardResponse<T>>;
|
|
394
|
+
/**
|
|
395
|
+
* Deletes the record using an HTTP DELETE request.
|
|
396
|
+
* @param options Additional request options.
|
|
397
|
+
* @returns A promise that resolves to a standard response object with a null data payload.
|
|
398
|
+
*/
|
|
399
|
+
remove: (options?: ActionOptions) => Promise<StandardResponse<null>>;
|
|
400
|
+
/**
|
|
401
|
+
* Resets the hook's state to its initial value.
|
|
402
|
+
*/
|
|
403
|
+
resetState: () => void;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Defines the configuration options for the `useApiRecord` hook.
|
|
407
|
+
* @template T The data type of the record.
|
|
408
|
+
*/
|
|
409
|
+
interface UseApiRecordConfig<T> {
|
|
410
|
+
/**
|
|
411
|
+
* The base API endpoint template for the resource.
|
|
412
|
+
* Can contain placeholders like `{endpointName}`.
|
|
413
|
+
* @example 'v1/dynamic/{endpointName}'
|
|
414
|
+
*/
|
|
415
|
+
endpoint: string;
|
|
416
|
+
/**
|
|
417
|
+
* An object containing key-value pairs to replace placeholders in the endpoint template.
|
|
418
|
+
* @example { endpointName: 'products' }
|
|
419
|
+
*/
|
|
420
|
+
pathParams?: Record<string, string | number>;
|
|
421
|
+
/** The unique identifier of the record to fetch or modify. */
|
|
422
|
+
recordId?: string | number | null;
|
|
423
|
+
/** Optional initial data to populate the state before the first fetch is complete. */
|
|
424
|
+
initialData?: T | null;
|
|
425
|
+
/** If `false`, the hook will not automatically fetch data on mount. Defaults to `true`. */
|
|
426
|
+
enabled?: boolean;
|
|
427
|
+
/** If `true`, the record will be refetched after a successful `update`, `put`, or `remove` action. Defaults to `true`. */
|
|
428
|
+
refetchAfterChange?: boolean;
|
|
429
|
+
/** Default `RequestConfig` to apply to the initial GET request made by the hook. */
|
|
430
|
+
requestConfig?: RequestConfig;
|
|
431
|
+
/** A callback function executed on a successful API action. */
|
|
432
|
+
onSuccess?: (message: string, data?: any) => void;
|
|
433
|
+
/** A callback function executed on a failed API action. */
|
|
434
|
+
onError?: (message: string, error?: ApiError) => void;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* The return value of the `useApiRecord` hook.
|
|
438
|
+
* @template T The data type of the record.
|
|
439
|
+
*/
|
|
440
|
+
interface UseApiRecordReturn<T> {
|
|
441
|
+
/** The current state of the API request, including data, loading, and error status. */
|
|
442
|
+
state: UseApiRecordState<T>;
|
|
443
|
+
/** Action methods to manipulate the record. */
|
|
444
|
+
actions: UseApiRecordActions<T>;
|
|
445
|
+
/** A React dispatch function to manually set the hook's state. Use with caution. */
|
|
446
|
+
setState: Dispatch<SetStateAction<UseApiRecordState<T>>>;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* A React hook for managing the lifecycle of a single API resource (a record).
|
|
451
|
+
* It handles fetching, updating, replacing, and deleting a record, while managing
|
|
452
|
+
* loading, error, and data states. It supports dynamic path parameters for flexible API routing.
|
|
453
|
+
*
|
|
454
|
+
* @template T The data type of the record being managed.
|
|
455
|
+
* @param {AxiosInstance} axiosInstance - The configured Axios instance for making API calls.
|
|
456
|
+
* @param {UseApiRecordConfig<T>} config - Configuration options for the hook.
|
|
457
|
+
* @returns {UseApiRecordReturn<T>} An object containing the state, actions, and setState function.
|
|
458
|
+
*/
|
|
459
|
+
declare function useApiRecord<T>(axiosInstance: AxiosInstance, config: UseApiRecordConfig<T>): UseApiRecordReturn<T>;
|
|
460
|
+
|
|
461
|
+
type EffectCallback = () => (void | (() => void));
|
|
462
|
+
type DependencyList = readonly any[];
|
|
463
|
+
declare function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList): void;
|
|
464
|
+
|
|
465
|
+
declare const ApiModuleProvider: React$1.Provider<UseApiModuleReturn<any> | null>;
|
|
466
|
+
declare function useModuleContext<TModule extends ApiModuleConfig<any>>(): UseApiModuleReturn<TModule['actions']>;
|
|
467
|
+
declare function useApiModule<TActions extends Record<string, ActionConfigModule<any, any>>>(axiosInstance: AxiosInstance, moduleConfig: ApiModuleConfig<TActions>, options?: UseApiModuleOptions): UseApiModuleReturn<TActions>;
|
|
468
|
+
|
|
469
|
+
declare class GlobalStateManager {
|
|
470
|
+
private store;
|
|
471
|
+
/**
|
|
472
|
+
* يحصل على لقطة (snapshot) للحالة الحالية لمفتاح معين.
|
|
473
|
+
*/
|
|
474
|
+
getSnapshot<T>(key: string): ActionStateModule<T>;
|
|
475
|
+
/**
|
|
476
|
+
* يسجل دالة callback للاستماع إلى التغييرات على مفتاح معين.
|
|
477
|
+
* @returns دالة لإلغاء الاشتراك.
|
|
478
|
+
*/
|
|
479
|
+
subscribe(key: string, callback: () => void): () => void;
|
|
480
|
+
/**
|
|
481
|
+
* يحدّث الحالة لمفتاح معين ويقوم بإعلام جميع المشتركين.
|
|
482
|
+
*/
|
|
483
|
+
setState<T>(key: string, updater: (prevState: ActionStateModule<T>) => ActionStateModule<T>): void;
|
|
484
|
+
/**
|
|
485
|
+
* يجعل البيانات المرتبطة بمفتاح معين "قديمة" (stale).
|
|
486
|
+
*/
|
|
487
|
+
invalidate(key: string): void;
|
|
488
|
+
/**
|
|
489
|
+
* [نسخة محدثة وأكثر قوة]
|
|
490
|
+
* يجعل كل البيانات التي تبدأ بمفتاح معين "قديمة" (stale).
|
|
491
|
+
* @example invalidateByPrefix('myModule/list::') سيبطل كل صفحات القائمة.
|
|
492
|
+
*/
|
|
493
|
+
invalidateByPrefix(prefix: string): void;
|
|
494
|
+
/**
|
|
495
|
+
* Serializes the current state of the query store into a JSON string.
|
|
496
|
+
* This is used on the server to pass the initial state to the client.
|
|
497
|
+
* @returns A JSON string representing the dehydrated state.
|
|
498
|
+
*/
|
|
499
|
+
dehydrate(): string;
|
|
500
|
+
/**
|
|
501
|
+
* Merges a dehydrated state object into the current store.
|
|
502
|
+
* This is used on the client to hydrate the state received from the server.
|
|
503
|
+
* @param hydratedState - A JSON string from the `dehydrate` method.
|
|
504
|
+
*/
|
|
505
|
+
rehydrate(hydratedState: string): void;
|
|
506
|
+
}
|
|
507
|
+
declare const globalStateManager: GlobalStateManager;
|
|
448
508
|
|
|
449
|
-
|
|
509
|
+
/**
|
|
510
|
+
* @file src/hooks/useApi.types.ts
|
|
511
|
+
* @description This file defines the professional, publicly-facing types for the `useApi` hook,
|
|
512
|
+
* providing a clean and stable contract for consumers.
|
|
513
|
+
*/
|
|
450
514
|
|
|
451
515
|
/**
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
|
|
516
|
+
* Configuration object for the `useApi` hook.
|
|
517
|
+
* @template T The type of the data entity.
|
|
518
|
+
*/
|
|
519
|
+
/**
|
|
520
|
+
* A collection of callable functions for performing CRUD and other operations.
|
|
521
|
+
* These actions automatically handle state updates like loading and refetching.
|
|
522
|
+
* @template T The type of the data entity being managed.
|
|
523
|
+
*/
|
|
524
|
+
interface UseApiActions<T, TListItem = T extends (infer U)[] ? U : T> {
|
|
525
|
+
fetch: (querryOptions?: QueryOptions) => Promise<void>;
|
|
526
|
+
create: (newItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
|
|
527
|
+
put: (id: string | number, item: TListItem, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
|
|
528
|
+
update: (id: string | number, updatedItem: Partial<TListItem>, options?: ActionOptions) => Promise<StandardResponse<TListItem>>;
|
|
529
|
+
remove: (id: string | number, options?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
530
|
+
bulkRemove: (ids: Array<string | number>, options?: ActionOptions) => Promise<StandardResponse<any>>;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* The complete return type of the `useApi` hook.
|
|
534
|
+
* It encapsulates the state, actions, and query controls for a given API resource.
|
|
535
|
+
* @template T The type of the data entity being managed.
|
|
455
536
|
*/
|
|
456
|
-
|
|
537
|
+
interface UseApiReturn<T> {
|
|
538
|
+
state: StandardResponse<T>;
|
|
539
|
+
setState: React.Dispatch<React.SetStateAction<StandardResponse<T>>>;
|
|
540
|
+
actions: UseApiActions<T>;
|
|
541
|
+
query: UseApiQuery;
|
|
542
|
+
}
|
|
457
543
|
|
|
458
544
|
type ApiResourceStatus = 'idle' | 'loading' | 'success' | 'error';
|
|
459
545
|
interface UseApiResourceState<T> {
|
|
@@ -501,4 +587,4 @@ interface UseApiResourceReturn<T, TCreate, TUpdate, TPathParams> {
|
|
|
501
587
|
setQuery: React.Dispatch<React.SetStateAction<QueryOptions>>;
|
|
502
588
|
}
|
|
503
589
|
|
|
504
|
-
export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiModuleConfig, type ApiResourceStatus, type
|
|
590
|
+
export { type ActionConfig, type ActionConfigModule, type ActionOptions, type ActionState, type ActionStateModule, type ApiClientConfig, type ApiError, type ApiModuleConfig, ApiModuleProvider, type ApiResourceStatus, type ExecutableAction, type ExecuteOptions, type InputOf, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type ModuleStates, type OutputOf, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiModuleReturn, type UseApiQuery, type UseApiRecordActions, type UseApiRecordConfig, type UseApiRecordReturn, type UseApiRecordState, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, callDynamicApi, createApiActions, createApiClient, createApiServices, globalStateManager, processResponse, useApi, useApiModule, useApiRecord, useDeepCompareEffect, useModuleContext };
|