api-core-lib 12.0.9 → 12.0.11
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 +1 -0
- package/dist/{apiModule.types-2yhaJWN3.d.cts → apiModule.types-CpwGDEpG.d.cts} +2 -2
- package/dist/{apiModule.types-2yhaJWN3.d.ts → apiModule.types-CpwGDEpG.d.ts} +2 -2
- package/dist/client.cjs +864 -0
- package/dist/client.d.cts +28 -0
- package/dist/client.d.ts +28 -0
- package/dist/client.js +824 -0
- package/dist/index.cjs +2 -458
- package/dist/index.d.cts +5 -113
- package/dist/index.d.ts +5 -113
- package/dist/index.js +659 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +310 -1
- package/dist/useApiRecord.types-B45E0qux.d.cts +90 -0
- package/dist/useApiRecord.types-DlrlXL1t.d.ts +90 -0
- package/package.json +8 -3
package/dist/client.js
ADDED
|
@@ -0,0 +1,824 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
4
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
+
|
|
6
|
+
// src/hooks/useApi.ts
|
|
7
|
+
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
|
|
8
|
+
|
|
9
|
+
// src/core/processor.ts
|
|
10
|
+
import axios2 from "axios";
|
|
11
|
+
|
|
12
|
+
// src/core/utils.ts
|
|
13
|
+
import axios from "axios";
|
|
14
|
+
function isAxiosResponse(obj) {
|
|
15
|
+
return obj && obj.data !== void 0 && obj.status !== void 0 && obj.config !== void 0;
|
|
16
|
+
}
|
|
17
|
+
function buildPaginateQuery(options) {
|
|
18
|
+
const params = new URLSearchParams();
|
|
19
|
+
for (const key in options) {
|
|
20
|
+
const value = options[key];
|
|
21
|
+
if (value === null || value === void 0) {
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (key === "filter" && typeof value === "object" && !Array.isArray(value)) {
|
|
25
|
+
for (const filterKey in value) {
|
|
26
|
+
const filterValue = value[filterKey];
|
|
27
|
+
if (filterValue !== null && filterValue !== void 0) {
|
|
28
|
+
params.append(`filter[${filterKey}]`, String(filterValue));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
} else if (key === "sortBy" && Array.isArray(value)) {
|
|
32
|
+
value.forEach((sortItem) => {
|
|
33
|
+
if (sortItem && sortItem.key && sortItem.direction) {
|
|
34
|
+
params.append("sortBy[]", `${sortItem.key}:${sortItem.direction}`);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
} else {
|
|
38
|
+
params.append(key, String(value));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return params.toString();
|
|
42
|
+
}
|
|
43
|
+
function isServerError(error) {
|
|
44
|
+
return axios.isAxiosError(error) && error.response !== void 0;
|
|
45
|
+
}
|
|
46
|
+
function isNetworkError(error) {
|
|
47
|
+
return axios.isAxiosError(error) && error.response === void 0 && error.request !== void 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/core/processor.ts
|
|
51
|
+
var processResponse = (responseOrError) => {
|
|
52
|
+
if (isAxiosResponse(responseOrError)) {
|
|
53
|
+
const response = responseOrError;
|
|
54
|
+
const rawData = response.data;
|
|
55
|
+
const isStandardApiResponse = rawData && typeof rawData.success === "boolean" && rawData.data !== void 0;
|
|
56
|
+
return {
|
|
57
|
+
data: isStandardApiResponse ? rawData.data : rawData,
|
|
58
|
+
links: isStandardApiResponse ? rawData.links : void 0,
|
|
59
|
+
meta: isStandardApiResponse ? rawData.meta : void 0,
|
|
60
|
+
rawResponse: rawData,
|
|
61
|
+
loading: false,
|
|
62
|
+
success: true,
|
|
63
|
+
error: null,
|
|
64
|
+
message: isStandardApiResponse ? rawData.message : "Request successful.",
|
|
65
|
+
validationErrors: []
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (isServerError(responseOrError)) {
|
|
69
|
+
const error = responseOrError;
|
|
70
|
+
const responseData = error.response.data;
|
|
71
|
+
const status = error.response.status;
|
|
72
|
+
let defaultMessage = "An unexpected server error occurred.";
|
|
73
|
+
switch (status) {
|
|
74
|
+
case 400:
|
|
75
|
+
defaultMessage = "Bad Request";
|
|
76
|
+
break;
|
|
77
|
+
case 401:
|
|
78
|
+
defaultMessage = "Unauthorized";
|
|
79
|
+
break;
|
|
80
|
+
case 403:
|
|
81
|
+
defaultMessage = "Forbidden";
|
|
82
|
+
break;
|
|
83
|
+
case 404:
|
|
84
|
+
defaultMessage = "Not Found";
|
|
85
|
+
break;
|
|
86
|
+
case 422:
|
|
87
|
+
defaultMessage = "Validation Failed";
|
|
88
|
+
break;
|
|
89
|
+
case 500:
|
|
90
|
+
defaultMessage = "Internal Server Error";
|
|
91
|
+
break;
|
|
92
|
+
case 503:
|
|
93
|
+
defaultMessage = "Service Unavailable";
|
|
94
|
+
break;
|
|
95
|
+
default:
|
|
96
|
+
defaultMessage = `Server Error (${status})`;
|
|
97
|
+
}
|
|
98
|
+
const finalApiError = {
|
|
99
|
+
message: responseData?.message || defaultMessage,
|
|
100
|
+
status,
|
|
101
|
+
code: responseData?.code || error.code,
|
|
102
|
+
errors: responseData?.errors || []
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
data: null,
|
|
106
|
+
rawResponse: responseData,
|
|
107
|
+
error: finalApiError,
|
|
108
|
+
validationErrors: finalApiError.errors,
|
|
109
|
+
success: false,
|
|
110
|
+
loading: false,
|
|
111
|
+
message: finalApiError.message
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
if (isNetworkError(responseOrError)) {
|
|
115
|
+
const error = responseOrError;
|
|
116
|
+
return {
|
|
117
|
+
data: null,
|
|
118
|
+
rawResponse: error.request,
|
|
119
|
+
error: { message: "Network Error: Unable to connect.", status: 0, code: error.code },
|
|
120
|
+
success: false,
|
|
121
|
+
loading: false,
|
|
122
|
+
message: "Network Error."
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
if (axios2.isCancel(responseOrError)) {
|
|
126
|
+
return {
|
|
127
|
+
data: null,
|
|
128
|
+
rawResponse: null,
|
|
129
|
+
error: { message: "Request Canceled.", status: 499 },
|
|
130
|
+
success: false,
|
|
131
|
+
loading: false,
|
|
132
|
+
message: "Request Canceled."
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
data: null,
|
|
137
|
+
rawResponse: responseOrError,
|
|
138
|
+
error: { message: "An unknown error occurred.", status: -1 },
|
|
139
|
+
success: false,
|
|
140
|
+
loading: false,
|
|
141
|
+
message: "An unknown error occurred."
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/core/buildDynamicUrl.ts
|
|
146
|
+
function buildDynamicUrl(template, params) {
|
|
147
|
+
if (!params) {
|
|
148
|
+
return template;
|
|
149
|
+
}
|
|
150
|
+
return template.replace(/\{(\w+)\}/g, (placeholder, key) => {
|
|
151
|
+
return params.hasOwnProperty(key) ? String(params[key]) : placeholder;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/services/crud.ts
|
|
156
|
+
function createApiServices(axiosInstance, baseEndpoint) {
|
|
157
|
+
const resolveUrl = (config = {}, id) => {
|
|
158
|
+
const endpointTemplate = config.endpoint || (id != null ? `${baseEndpoint}/{id}` : baseEndpoint);
|
|
159
|
+
const params = id != null ? { id, tenant: id, tenantId: id, recordId: id } : {};
|
|
160
|
+
return buildDynamicUrl(endpointTemplate, params);
|
|
161
|
+
};
|
|
162
|
+
const get = async (id, config) => {
|
|
163
|
+
const url = resolveUrl(config, id);
|
|
164
|
+
try {
|
|
165
|
+
const response = await axiosInstance.get(url, config);
|
|
166
|
+
return processResponse(response);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return processResponse(error);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const getWithQuery = async (query, config) => {
|
|
172
|
+
const url = `${baseEndpoint}?${query}`;
|
|
173
|
+
try {
|
|
174
|
+
const response = await axiosInstance.get(url, config);
|
|
175
|
+
return processResponse(response);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
return processResponse(error);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
const post = async (data, config) => {
|
|
181
|
+
const url = resolveUrl(config);
|
|
182
|
+
try {
|
|
183
|
+
const response = await axiosInstance.post(url, data, config);
|
|
184
|
+
console.log("[lib] response POST: ", response);
|
|
185
|
+
console.log("[lib] response processResponse POST: ", processResponse(response));
|
|
186
|
+
return processResponse(response);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
console.log("[lib] response error POST: ", processResponse(error));
|
|
189
|
+
return processResponse(error);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
const put = async (id, data, config) => {
|
|
193
|
+
const url = resolveUrl(config, id);
|
|
194
|
+
try {
|
|
195
|
+
const response = await axiosInstance.put(url, data, config);
|
|
196
|
+
return processResponse(response);
|
|
197
|
+
} catch (error) {
|
|
198
|
+
return processResponse(error);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
const patch = async (id, data, config) => {
|
|
202
|
+
const url = resolveUrl(config, id);
|
|
203
|
+
try {
|
|
204
|
+
const response = await axiosInstance.patch(url, data, config);
|
|
205
|
+
return processResponse(response);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
return processResponse(error);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
const remove = async (id, config) => {
|
|
211
|
+
const url = resolveUrl(config, id);
|
|
212
|
+
try {
|
|
213
|
+
const response = await axiosInstance.delete(url, config);
|
|
214
|
+
return processResponse(response);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
return processResponse(error);
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const bulkDelete = async (ids, config) => {
|
|
220
|
+
const url = resolveUrl(config);
|
|
221
|
+
try {
|
|
222
|
+
const response = await axiosInstance.delete(url, { data: { ids }, ...config });
|
|
223
|
+
return processResponse(response);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
return processResponse(error);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
const upload = async (file, additionalData, config) => {
|
|
229
|
+
const url = resolveUrl(config);
|
|
230
|
+
const formData = new FormData();
|
|
231
|
+
formData.append("file", file);
|
|
232
|
+
if (additionalData) {
|
|
233
|
+
Object.keys(additionalData).forEach((key) => formData.append(key, String(additionalData[key])));
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
const response = await axiosInstance.post(url, formData, {
|
|
237
|
+
...config,
|
|
238
|
+
headers: { ...config?.headers, "Content-Type": "multipart/form-data" }
|
|
239
|
+
});
|
|
240
|
+
return processResponse(response);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
return processResponse(error);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
return { get, getWithQuery, post, put, patch, remove, bulkDelete, upload };
|
|
246
|
+
}
|
|
247
|
+
async function callDynamicApi(axiosInstance, baseEndpoint, actionConfig, params) {
|
|
248
|
+
const { pathParams, body, config } = params;
|
|
249
|
+
const urlTemplate = `${baseEndpoint}${actionConfig.path}`;
|
|
250
|
+
const finalUrl = buildDynamicUrl(urlTemplate, pathParams || {});
|
|
251
|
+
try {
|
|
252
|
+
const { method } = actionConfig;
|
|
253
|
+
let response;
|
|
254
|
+
if (method === "POST" || method === "PUT" || method === "PATCH") {
|
|
255
|
+
response = await axiosInstance[method.toLowerCase()](finalUrl, body, config);
|
|
256
|
+
} else if (method === "DELETE") {
|
|
257
|
+
response = await axiosInstance.delete(finalUrl, { data: body, ...config });
|
|
258
|
+
} else {
|
|
259
|
+
response = await axiosInstance.get(finalUrl, { params: body, ...config });
|
|
260
|
+
}
|
|
261
|
+
return processResponse(response);
|
|
262
|
+
} catch (error) {
|
|
263
|
+
return processResponse(error);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/hooks/useApi.ts
|
|
268
|
+
function buildDynamicPath(template, params) {
|
|
269
|
+
if (!params) return template;
|
|
270
|
+
let path = template;
|
|
271
|
+
for (const key in params) {
|
|
272
|
+
path = path.replace(new RegExp(`{${key}}`, "g"), String(params[key]));
|
|
273
|
+
}
|
|
274
|
+
return path;
|
|
275
|
+
}
|
|
276
|
+
function useApi(axiosInstance, config) {
|
|
277
|
+
const {
|
|
278
|
+
endpoint,
|
|
279
|
+
pathParams,
|
|
280
|
+
// [REMOVE] لم نعد بحاجة لهذا الخيار
|
|
281
|
+
// encodeQuery = true,
|
|
282
|
+
initialData,
|
|
283
|
+
initialQuery = {},
|
|
284
|
+
enabled = true,
|
|
285
|
+
refetchAfterChange = true,
|
|
286
|
+
requestConfig,
|
|
287
|
+
onSuccess,
|
|
288
|
+
onError
|
|
289
|
+
} = config;
|
|
290
|
+
const finalEndpoint = useMemo(
|
|
291
|
+
() => buildDynamicPath(endpoint, pathParams),
|
|
292
|
+
[endpoint, pathParams]
|
|
293
|
+
);
|
|
294
|
+
const [state, setState] = useState({
|
|
295
|
+
data: initialData ?? null,
|
|
296
|
+
rawResponse: null,
|
|
297
|
+
loading: enabled,
|
|
298
|
+
error: null,
|
|
299
|
+
success: false,
|
|
300
|
+
message: void 0,
|
|
301
|
+
validationErrors: void 0
|
|
302
|
+
});
|
|
303
|
+
const [queryOptions, setQueryOptions] = useState(initialQuery);
|
|
304
|
+
const apiServices = useMemo(
|
|
305
|
+
() => createApiServices(axiosInstance, finalEndpoint),
|
|
306
|
+
[axiosInstance, finalEndpoint]
|
|
307
|
+
);
|
|
308
|
+
const savedOnSuccess = useRef(onSuccess);
|
|
309
|
+
const savedOnError = useRef(onError);
|
|
310
|
+
useEffect(() => {
|
|
311
|
+
savedOnSuccess.current = onSuccess;
|
|
312
|
+
savedOnError.current = onError;
|
|
313
|
+
}, [onSuccess, onError]);
|
|
314
|
+
const fetchData = useCallback(async (currentQueryOptions) => {
|
|
315
|
+
setState((prev) => ({ ...prev, loading: true, error: null }));
|
|
316
|
+
try {
|
|
317
|
+
const finalQuery = currentQueryOptions || queryOptions;
|
|
318
|
+
const hasQueryParams = Object.keys(finalQuery).length > 0;
|
|
319
|
+
const queryString = buildPaginateQuery(finalQuery);
|
|
320
|
+
const result = hasQueryParams ? await apiServices.getWithQuery(queryString, requestConfig) : await apiServices.get(void 0, requestConfig);
|
|
321
|
+
setState(result);
|
|
322
|
+
if (result.success && savedOnSuccess.current) {
|
|
323
|
+
savedOnSuccess.current(result.message || "Fetch successful!", result.data ?? void 0);
|
|
324
|
+
} else if (!result.success && savedOnError.current) {
|
|
325
|
+
savedOnError.current(result.message || "Fetch failed", result.error ?? void 0);
|
|
326
|
+
}
|
|
327
|
+
} catch (e) {
|
|
328
|
+
const apiError = { status: 500, message: e.message || "An unexpected client-side error occurred." };
|
|
329
|
+
setState((prev) => ({ ...prev, loading: false, error: apiError, success: false }));
|
|
330
|
+
if (savedOnError.current) {
|
|
331
|
+
savedOnError.current(apiError.message, apiError);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}, [apiServices, queryOptions, requestConfig]);
|
|
335
|
+
useEffect(() => {
|
|
336
|
+
if (enabled) {
|
|
337
|
+
fetchData();
|
|
338
|
+
}
|
|
339
|
+
}, [enabled, fetchData]);
|
|
340
|
+
const handleActionResult = useCallback(async (actionPromise) => {
|
|
341
|
+
setState((prev) => ({ ...prev, loading: true }));
|
|
342
|
+
try {
|
|
343
|
+
const result = await actionPromise;
|
|
344
|
+
if (result.success) {
|
|
345
|
+
if (savedOnSuccess.current) {
|
|
346
|
+
savedOnSuccess.current(result.message || "Action successful!", result.data ?? void 0);
|
|
347
|
+
}
|
|
348
|
+
if (refetchAfterChange) {
|
|
349
|
+
await fetchData(queryOptions);
|
|
350
|
+
} else {
|
|
351
|
+
setState((prev) => ({ ...prev, ...result, loading: false }));
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
354
|
+
if (savedOnError.current) {
|
|
355
|
+
savedOnError.current(result.message || "Action failed", result.error ?? void 0);
|
|
356
|
+
}
|
|
357
|
+
setState((prev) => ({ ...prev, loading: false, error: result.error, success: false }));
|
|
358
|
+
}
|
|
359
|
+
return result;
|
|
360
|
+
} catch (e) {
|
|
361
|
+
const apiError = { status: 500, message: e.message || "An unexpected error occurred during action." };
|
|
362
|
+
setState((prev) => ({ ...prev, loading: false, error: apiError, success: false }));
|
|
363
|
+
if (savedOnError.current) {
|
|
364
|
+
savedOnError.current(apiError.message, apiError);
|
|
365
|
+
}
|
|
366
|
+
return { data: null, error: apiError, loading: false, success: false, rawResponse: e };
|
|
367
|
+
}
|
|
368
|
+
}, [refetchAfterChange, fetchData, queryOptions]);
|
|
369
|
+
const actions = {
|
|
370
|
+
fetch: fetchData,
|
|
371
|
+
create: (newItem, options) => handleActionResult(apiServices.post(newItem, options)),
|
|
372
|
+
put: (id, item, options) => handleActionResult(apiServices.put(id, item, options)),
|
|
373
|
+
update: (id, updatedItem, options) => handleActionResult(apiServices.patch(id, updatedItem, options)),
|
|
374
|
+
remove: (id, options) => handleActionResult(apiServices.remove(id, options)),
|
|
375
|
+
bulkRemove: (ids, options) => handleActionResult(apiServices.bulkDelete(ids, options))
|
|
376
|
+
};
|
|
377
|
+
const query = {
|
|
378
|
+
options: queryOptions,
|
|
379
|
+
setOptions: setQueryOptions,
|
|
380
|
+
setPage: (page) => setQueryOptions((prev) => ({ ...prev, page })),
|
|
381
|
+
setLimit: (limit) => setQueryOptions((prev) => ({ ...prev, page: 1, limit })),
|
|
382
|
+
setSearchTerm: (search) => setQueryOptions((prev) => ({ ...prev, page: 1, search })),
|
|
383
|
+
setSorting: (sortBy) => setQueryOptions((prev) => ({ ...prev, sortBy })),
|
|
384
|
+
setFilters: (filter) => setQueryOptions((prev) => ({ ...prev, page: 1, filter })),
|
|
385
|
+
setQueryParam: (key, value) => setQueryOptions((prev) => ({ ...prev, [key]: value, page: key !== "page" ? 1 : value })),
|
|
386
|
+
reset: () => setQueryOptions(initialQuery)
|
|
387
|
+
};
|
|
388
|
+
return { state, setState, actions, query };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/hooks/useApiRecord/index.ts
|
|
392
|
+
import { useState as useState2, useEffect as useEffect2, useCallback as useCallback2, useRef as useRef2, useMemo as useMemo2 } from "react";
|
|
393
|
+
function buildDynamicPath2(template, params) {
|
|
394
|
+
if (!params) return template;
|
|
395
|
+
let path = template;
|
|
396
|
+
for (const key in params) {
|
|
397
|
+
path = path.replace(new RegExp(`{${key}}`, "g"), String(params[key]));
|
|
398
|
+
}
|
|
399
|
+
return path;
|
|
400
|
+
}
|
|
401
|
+
function useApiRecord(axiosInstance, config) {
|
|
402
|
+
const {
|
|
403
|
+
endpoint,
|
|
404
|
+
pathParams,
|
|
405
|
+
recordId,
|
|
406
|
+
initialData,
|
|
407
|
+
enabled = true,
|
|
408
|
+
refetchAfterChange = true,
|
|
409
|
+
requestConfig,
|
|
410
|
+
onSuccess,
|
|
411
|
+
onError
|
|
412
|
+
} = config;
|
|
413
|
+
const finalEndpoint = useMemo2(
|
|
414
|
+
() => buildDynamicPath2(endpoint, pathParams),
|
|
415
|
+
[endpoint, pathParams]
|
|
416
|
+
);
|
|
417
|
+
const initialState = useMemo2(() => ({
|
|
418
|
+
data: initialData ?? null,
|
|
419
|
+
rawResponse: null,
|
|
420
|
+
error: null,
|
|
421
|
+
loading: enabled && !!recordId,
|
|
422
|
+
success: false,
|
|
423
|
+
message: void 0,
|
|
424
|
+
validationErrors: void 0
|
|
425
|
+
}), [initialData, enabled, recordId]);
|
|
426
|
+
const [state, setState] = useState2(initialState);
|
|
427
|
+
const savedOnSuccess = useRef2(onSuccess);
|
|
428
|
+
const savedOnError = useRef2(onError);
|
|
429
|
+
useEffect2(() => {
|
|
430
|
+
savedOnSuccess.current = onSuccess;
|
|
431
|
+
savedOnError.current = onError;
|
|
432
|
+
}, [onSuccess, onError]);
|
|
433
|
+
const apiServices = useMemo2(
|
|
434
|
+
() => createApiServices(axiosInstance, finalEndpoint),
|
|
435
|
+
[axiosInstance, finalEndpoint]
|
|
436
|
+
);
|
|
437
|
+
const fetchRecord = useCallback2(async () => {
|
|
438
|
+
if (!recordId) {
|
|
439
|
+
setState(initialState);
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
setState((prev) => ({ ...prev, loading: true, error: null, success: false }));
|
|
443
|
+
try {
|
|
444
|
+
const result = await apiServices.get(recordId, requestConfig);
|
|
445
|
+
setState(result);
|
|
446
|
+
if (result.success && savedOnSuccess.current) {
|
|
447
|
+
savedOnSuccess.current(result.message || "Record fetched successfully!", result.data ?? void 0);
|
|
448
|
+
} else if (!result.success && savedOnError.current) {
|
|
449
|
+
savedOnError.current(result.message || "Fetch failed", result.error ?? void 0);
|
|
450
|
+
}
|
|
451
|
+
} catch (e) {
|
|
452
|
+
console.error("[useApiRecord Fetch Error]", e);
|
|
453
|
+
const apiError = {
|
|
454
|
+
status: e.response?.status || 500,
|
|
455
|
+
message: e.message || "An unexpected client-side error occurred.",
|
|
456
|
+
code: e.code
|
|
457
|
+
};
|
|
458
|
+
setState((prev) => ({ ...prev, loading: false, success: false, error: apiError }));
|
|
459
|
+
if (savedOnError.current) {
|
|
460
|
+
savedOnError.current(apiError.message, apiError);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}, [apiServices, recordId, requestConfig, initialState]);
|
|
464
|
+
useEffect2(() => {
|
|
465
|
+
if (enabled) {
|
|
466
|
+
fetchRecord();
|
|
467
|
+
}
|
|
468
|
+
}, [enabled, fetchRecord]);
|
|
469
|
+
const handleActionResult = useCallback2(
|
|
470
|
+
async (actionPromise, options) => {
|
|
471
|
+
setState((prev) => ({ ...prev, loading: true }));
|
|
472
|
+
try {
|
|
473
|
+
const result = await actionPromise;
|
|
474
|
+
if (result.success) {
|
|
475
|
+
if (savedOnSuccess.current) {
|
|
476
|
+
savedOnSuccess.current(result.message || "Action successful!", result.data);
|
|
477
|
+
}
|
|
478
|
+
const shouldRefetch = options?.refetch ?? refetchAfterChange;
|
|
479
|
+
if (shouldRefetch) {
|
|
480
|
+
await fetchRecord();
|
|
481
|
+
} else {
|
|
482
|
+
setState({ ...result, loading: false, data: result.data });
|
|
483
|
+
}
|
|
484
|
+
} else {
|
|
485
|
+
if (savedOnError.current) {
|
|
486
|
+
savedOnError.current(result.message || "Action failed", result.error ?? void 0);
|
|
487
|
+
}
|
|
488
|
+
setState((prev) => ({ ...prev, ...result, loading: false }));
|
|
489
|
+
}
|
|
490
|
+
return result;
|
|
491
|
+
} catch (e) {
|
|
492
|
+
console.error("[useApiRecord Action Error]", e);
|
|
493
|
+
const apiError = {
|
|
494
|
+
status: e.response?.status || 500,
|
|
495
|
+
message: e.message || "An unexpected error occurred during the action.",
|
|
496
|
+
code: e.code
|
|
497
|
+
};
|
|
498
|
+
const errorResponse = { ...initialState, loading: false, success: false, error: apiError, rawResponse: e, data: null };
|
|
499
|
+
setState(errorResponse);
|
|
500
|
+
if (savedOnError.current) {
|
|
501
|
+
savedOnError.current(apiError.message, apiError);
|
|
502
|
+
}
|
|
503
|
+
return errorResponse;
|
|
504
|
+
}
|
|
505
|
+
},
|
|
506
|
+
[refetchAfterChange, fetchRecord, initialState]
|
|
507
|
+
);
|
|
508
|
+
const actions = {
|
|
509
|
+
fetch: fetchRecord,
|
|
510
|
+
update: (updatedItem, options) => handleActionResult(apiServices.patch(recordId, updatedItem, { ...requestConfig, ...options }), options),
|
|
511
|
+
put: (item, options) => handleActionResult(apiServices.put(recordId, item, { ...requestConfig, ...options }), options),
|
|
512
|
+
remove: (options) => handleActionResult(apiServices.remove(recordId, { ...requestConfig, ...options }), options),
|
|
513
|
+
resetState: () => setState(initialState)
|
|
514
|
+
};
|
|
515
|
+
return { state, setState, actions };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// src/hooks/useDeepCompareEffect/index.ts
|
|
519
|
+
import { useEffect as useEffect3, useRef as useRef3 } from "react";
|
|
520
|
+
import isEqual from "fast-deep-equal";
|
|
521
|
+
function useDeepCompareEffect(callback, dependencies) {
|
|
522
|
+
const currentDependenciesRef = useRef3();
|
|
523
|
+
if (!isEqual(currentDependenciesRef.current, dependencies)) {
|
|
524
|
+
currentDependenciesRef.current = dependencies;
|
|
525
|
+
}
|
|
526
|
+
useEffect3(callback, [currentDependenciesRef.current]);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// src/hooks/useApiModule/useApiModule.ts
|
|
530
|
+
import { createContext, useContext, useEffect as useEffect4, useMemo as useMemo3, useRef as useRef4, useState as useState3, useSyncExternalStore } from "react";
|
|
531
|
+
|
|
532
|
+
// src/core/globalStateManager.ts
|
|
533
|
+
var createInitialState = () => ({
|
|
534
|
+
data: null,
|
|
535
|
+
links: void 0,
|
|
536
|
+
meta: void 0,
|
|
537
|
+
error: null,
|
|
538
|
+
loading: false,
|
|
539
|
+
success: false,
|
|
540
|
+
called: false,
|
|
541
|
+
isStale: false,
|
|
542
|
+
message: void 0,
|
|
543
|
+
validationErrors: [],
|
|
544
|
+
rawResponse: null
|
|
545
|
+
});
|
|
546
|
+
var GlobalStateManager = class {
|
|
547
|
+
constructor() {
|
|
548
|
+
__publicField(this, "store", /* @__PURE__ */ new Map());
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* يحصل على لقطة (snapshot) للحالة الحالية لمفتاح معين.
|
|
552
|
+
*/
|
|
553
|
+
getSnapshot(key) {
|
|
554
|
+
return this.store.get(key)?.state ?? createInitialState();
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* يسجل دالة callback للاستماع إلى التغييرات على مفتاح معين.
|
|
558
|
+
* @returns دالة لإلغاء الاشتراك.
|
|
559
|
+
*/
|
|
560
|
+
subscribe(key, callback) {
|
|
561
|
+
if (!this.store.has(key)) {
|
|
562
|
+
this.store.set(key, { state: createInitialState(), listeners: /* @__PURE__ */ new Set() });
|
|
563
|
+
}
|
|
564
|
+
const item = this.store.get(key);
|
|
565
|
+
item.listeners.add(callback);
|
|
566
|
+
return () => {
|
|
567
|
+
item.listeners.delete(callback);
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* يحدّث الحالة لمفتاح معين ويقوم بإعلام جميع المشتركين.
|
|
572
|
+
*/
|
|
573
|
+
setState(key, updater) {
|
|
574
|
+
const currentState = this.getSnapshot(key);
|
|
575
|
+
const newState = updater(currentState);
|
|
576
|
+
if (!this.store.has(key)) {
|
|
577
|
+
this.store.set(key, { state: newState, listeners: /* @__PURE__ */ new Set() });
|
|
578
|
+
} else {
|
|
579
|
+
this.store.get(key).state = newState;
|
|
580
|
+
}
|
|
581
|
+
this.store.get(key).listeners.forEach((listener) => listener());
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* يجعل البيانات المرتبطة بمفتاح معين "قديمة" (stale).
|
|
585
|
+
*/
|
|
586
|
+
invalidate(key) {
|
|
587
|
+
const state = this.getSnapshot(key);
|
|
588
|
+
if (state.called) {
|
|
589
|
+
this.setState(key, (prev) => ({ ...prev, isStale: true }));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* [نسخة محدثة وأكثر قوة]
|
|
594
|
+
* يجعل كل البيانات التي تبدأ بمفتاح معين "قديمة" (stale).
|
|
595
|
+
* @example invalidateByPrefix('myModule/list::') سيبطل كل صفحات القائمة.
|
|
596
|
+
*/
|
|
597
|
+
invalidateByPrefix(prefix) {
|
|
598
|
+
this.store.forEach((value, key) => {
|
|
599
|
+
if (key.startsWith(prefix)) {
|
|
600
|
+
const state = this.getSnapshot(key);
|
|
601
|
+
if (state.called) {
|
|
602
|
+
this.setState(key, (prev) => ({ ...prev, isStale: true }));
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Serializes the current state of the query store into a JSON string.
|
|
609
|
+
* This is used on the server to pass the initial state to the client.
|
|
610
|
+
* @returns A JSON string representing the dehydrated state.
|
|
611
|
+
*/
|
|
612
|
+
dehydrate() {
|
|
613
|
+
const stateToPersist = {};
|
|
614
|
+
this.store.forEach((value, key) => {
|
|
615
|
+
if (value.state.called) {
|
|
616
|
+
stateToPersist[key] = value.state;
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
return JSON.stringify(stateToPersist);
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Merges a dehydrated state object into the current store.
|
|
623
|
+
* This is used on the client to hydrate the state received from the server.
|
|
624
|
+
* @param hydratedState - A JSON string from the `dehydrate` method.
|
|
625
|
+
*/
|
|
626
|
+
rehydrate(hydratedState) {
|
|
627
|
+
try {
|
|
628
|
+
const parsedState = JSON.parse(hydratedState);
|
|
629
|
+
for (const key in parsedState) {
|
|
630
|
+
this.setState(key, () => parsedState[key]);
|
|
631
|
+
}
|
|
632
|
+
} catch (e) {
|
|
633
|
+
console.error("[api-core-lib] Failed to rehydrate state:", e);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
var globalStateManager = new GlobalStateManager();
|
|
638
|
+
|
|
639
|
+
// src/hooks/useApiModule/useApiModule.ts
|
|
640
|
+
var ApiModuleContext = createContext(null);
|
|
641
|
+
var ApiModuleProvider = ApiModuleContext.Provider;
|
|
642
|
+
function useModuleContext() {
|
|
643
|
+
const context = useContext(ApiModuleContext);
|
|
644
|
+
if (!context) {
|
|
645
|
+
throw new Error("useModuleContext must be used within an ApiModuleProvider");
|
|
646
|
+
}
|
|
647
|
+
return context;
|
|
648
|
+
}
|
|
649
|
+
var generateCacheKey = (moduleName, actionName, input, callOptions = {}) => {
|
|
650
|
+
const params = { path: callOptions.pathParams, body: input };
|
|
651
|
+
try {
|
|
652
|
+
return `${moduleName}/${actionName}::${JSON.stringify(params)}`;
|
|
653
|
+
} catch (error) {
|
|
654
|
+
return `${moduleName}/${actionName}::${Date.now()}`;
|
|
655
|
+
}
|
|
656
|
+
};
|
|
657
|
+
function useApiModule(axiosInstance, moduleConfig, options = {}) {
|
|
658
|
+
const { refetchOnWindowFocus = true, onSuccess, onError, pathParams: modulePathParams, enabled = true, hydratedState } = options;
|
|
659
|
+
const pathParamsString = useMemo3(() => JSON.stringify(modulePathParams || {}), [modulePathParams]);
|
|
660
|
+
const [queryOptions, setQueryOptions] = useState3({});
|
|
661
|
+
const savedCallbacks = useRef4({ onSuccess, onError });
|
|
662
|
+
useEffect4(() => {
|
|
663
|
+
savedCallbacks.current = { onSuccess, onError };
|
|
664
|
+
}, [onSuccess, onError]);
|
|
665
|
+
useMemo3(() => {
|
|
666
|
+
if (hydratedState) {
|
|
667
|
+
globalStateManager.rehydrate(hydratedState);
|
|
668
|
+
}
|
|
669
|
+
}, [hydratedState]);
|
|
670
|
+
const actions = useMemo3(() => {
|
|
671
|
+
return Object.keys(moduleConfig.actions).reduce((acc, actionName) => {
|
|
672
|
+
const actionConfig = moduleConfig.actions[actionName];
|
|
673
|
+
const execute = async (input, options2 = {}) => {
|
|
674
|
+
const finalPathParams = { ...JSON.parse(pathParamsString), ...options2.pathParams };
|
|
675
|
+
const cacheKey = generateCacheKey(moduleConfig.baseEndpoint, actionName, input, { pathParams: finalPathParams });
|
|
676
|
+
let mutationContext;
|
|
677
|
+
try {
|
|
678
|
+
if (options2.onMutate) {
|
|
679
|
+
mutationContext = await options2.onMutate(input);
|
|
680
|
+
}
|
|
681
|
+
globalStateManager.setState(cacheKey, (prev) => ({ ...prev, loading: true, called: true, error: null, isStale: false }));
|
|
682
|
+
const result = await callDynamicApi(axiosInstance, moduleConfig.baseEndpoint, actionConfig, {
|
|
683
|
+
pathParams: finalPathParams,
|
|
684
|
+
body: input,
|
|
685
|
+
config: options2.config
|
|
686
|
+
});
|
|
687
|
+
globalStateManager.setState(cacheKey, (prev) => ({ ...prev, ...result, loading: false }));
|
|
688
|
+
if (result.success) {
|
|
689
|
+
savedCallbacks.current.onSuccess?.(actionName, result.message || "Action successful", result.data);
|
|
690
|
+
options2.onSuccess?.(result.data, mutationContext);
|
|
691
|
+
actionConfig.invalidates?.forEach((keyToInvalidate) => {
|
|
692
|
+
const prefix = `${moduleConfig.baseEndpoint}/${keyToInvalidate}::`;
|
|
693
|
+
globalStateManager.invalidateByPrefix(prefix);
|
|
694
|
+
});
|
|
695
|
+
} else {
|
|
696
|
+
savedCallbacks.current.onError?.(actionName, result.message || "Action failed", result.error ?? void 0);
|
|
697
|
+
options2.onError?.(result.error, mutationContext);
|
|
698
|
+
}
|
|
699
|
+
return result;
|
|
700
|
+
} catch (error) {
|
|
701
|
+
const apiError = { status: 500, message: error.message };
|
|
702
|
+
const errorResult = { data: null, error: apiError, loading: false, success: false, rawResponse: error };
|
|
703
|
+
globalStateManager.setState(cacheKey, (prev) => ({ ...prev, ...errorResult, loading: false }));
|
|
704
|
+
savedCallbacks.current.onError?.(actionName, apiError.message, apiError);
|
|
705
|
+
options2.onError?.(apiError, mutationContext);
|
|
706
|
+
return errorResult;
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
const reset = (input, options2 = {}) => {
|
|
710
|
+
const finalPathParams = { ...JSON.parse(pathParamsString), ...options2.pathParams };
|
|
711
|
+
const cacheKey = generateCacheKey(moduleConfig.baseEndpoint, actionName, input, { pathParams: finalPathParams });
|
|
712
|
+
globalStateManager.setState(cacheKey, () => ({
|
|
713
|
+
data: null,
|
|
714
|
+
error: null,
|
|
715
|
+
loading: false,
|
|
716
|
+
success: false,
|
|
717
|
+
called: false,
|
|
718
|
+
isStale: false,
|
|
719
|
+
rawResponse: null
|
|
720
|
+
}));
|
|
721
|
+
};
|
|
722
|
+
acc[actionName] = { execute, reset };
|
|
723
|
+
return acc;
|
|
724
|
+
}, {});
|
|
725
|
+
}, [axiosInstance, moduleConfig, pathParamsString]);
|
|
726
|
+
const queries = useMemo3(() => {
|
|
727
|
+
const builtQueries = {};
|
|
728
|
+
for (const actionName in moduleConfig.actions) {
|
|
729
|
+
if (moduleConfig.actions[actionName]?.hasQuery) {
|
|
730
|
+
const setActionQueryOptions = (updater) => {
|
|
731
|
+
setQueryOptions((prev) => ({ ...prev, [actionName]: typeof updater === "function" ? updater(prev[actionName] || {}) : updater }));
|
|
732
|
+
};
|
|
733
|
+
builtQueries[actionName] = {
|
|
734
|
+
options: queryOptions[actionName] || {},
|
|
735
|
+
setOptions: setActionQueryOptions,
|
|
736
|
+
setPage: (page) => setActionQueryOptions((p) => ({ ...p, page })),
|
|
737
|
+
setLimit: (limit) => setActionQueryOptions((p) => ({ ...p, limit, page: 1 })),
|
|
738
|
+
setSearchTerm: (search) => setActionQueryOptions((p) => ({ ...p, search, page: 1 })),
|
|
739
|
+
setFilters: (filter) => setActionQueryOptions((p) => ({ ...p, filter, page: 1 })),
|
|
740
|
+
setSorting: (sortBy) => setActionQueryOptions((p) => ({ ...p, sortBy })),
|
|
741
|
+
setQueryParam: (key, value) => setActionQueryOptions((p) => ({ ...p, [key]: value, page: key !== "page" ? value : p.page })),
|
|
742
|
+
reset: () => setActionQueryOptions({})
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
return builtQueries;
|
|
747
|
+
}, [queryOptions, moduleConfig.actions]);
|
|
748
|
+
const states = useMemo3(() => {
|
|
749
|
+
const finalStates = {};
|
|
750
|
+
for (const actionName of Object.keys(moduleConfig.actions)) {
|
|
751
|
+
Object.defineProperty(finalStates, actionName, {
|
|
752
|
+
get: () => {
|
|
753
|
+
const actionConfig = moduleConfig.actions[actionName];
|
|
754
|
+
const query = queries[actionName]?.options;
|
|
755
|
+
const input = actionConfig.hasQuery ? query : void 0;
|
|
756
|
+
const pathParams = JSON.parse(pathParamsString);
|
|
757
|
+
const cacheKey = generateCacheKey(moduleConfig.baseEndpoint, actionName, input, { pathParams });
|
|
758
|
+
const state = useSyncExternalStore(
|
|
759
|
+
(callback) => globalStateManager.subscribe(cacheKey, callback),
|
|
760
|
+
() => globalStateManager.getSnapshot(cacheKey)
|
|
761
|
+
);
|
|
762
|
+
useEffect4(() => {
|
|
763
|
+
if (enabled && state.isStale && !state.loading) {
|
|
764
|
+
actions[actionName].execute(input);
|
|
765
|
+
}
|
|
766
|
+
}, [enabled, state.isStale, state.loading, input, actions, actionName]);
|
|
767
|
+
return state;
|
|
768
|
+
},
|
|
769
|
+
enumerable: true
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
return finalStates;
|
|
773
|
+
}, [moduleConfig, pathParamsString, queries, enabled, actions]);
|
|
774
|
+
useEffect4(() => {
|
|
775
|
+
if (!enabled) return;
|
|
776
|
+
const actionKeys = Object.keys(moduleConfig.actions);
|
|
777
|
+
for (const actionName of actionKeys) {
|
|
778
|
+
const state = states[actionName];
|
|
779
|
+
const actionConfig = moduleConfig.actions[actionName];
|
|
780
|
+
if (actionConfig.autoFetch && state && !state.called && !state.loading) {
|
|
781
|
+
const query = queries[actionName]?.options;
|
|
782
|
+
const input = actionConfig.hasQuery ? query : void 0;
|
|
783
|
+
actions[actionName].execute(input);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}, [enabled, moduleConfig, actions, states, queries]);
|
|
787
|
+
const lastBlurTimestamp = useRef4(Date.now());
|
|
788
|
+
useEffect4(() => {
|
|
789
|
+
if (!enabled || !refetchOnWindowFocus) return;
|
|
790
|
+
const onFocus = () => {
|
|
791
|
+
if (Date.now() - lastBlurTimestamp.current > 1e4) {
|
|
792
|
+
const actionKeys = Object.keys(moduleConfig.actions);
|
|
793
|
+
for (const actionName of actionKeys) {
|
|
794
|
+
const state = states[actionName];
|
|
795
|
+
if (state && state.called && !state.loading) {
|
|
796
|
+
const prefix = `${moduleConfig.baseEndpoint}/${actionName}::`;
|
|
797
|
+
globalStateManager.invalidateByPrefix(prefix);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
const onBlur = () => {
|
|
803
|
+
lastBlurTimestamp.current = Date.now();
|
|
804
|
+
};
|
|
805
|
+
window.addEventListener("focus", onFocus);
|
|
806
|
+
window.addEventListener("blur", onBlur);
|
|
807
|
+
return () => {
|
|
808
|
+
window.removeEventListener("focus", onFocus);
|
|
809
|
+
window.removeEventListener("blur", onBlur);
|
|
810
|
+
};
|
|
811
|
+
}, [enabled, refetchOnWindowFocus, moduleConfig, states]);
|
|
812
|
+
const dehydrate = useMemo3(() => {
|
|
813
|
+
return () => globalStateManager.dehydrate();
|
|
814
|
+
}, []);
|
|
815
|
+
return { actions, states, queries, dehydrate };
|
|
816
|
+
}
|
|
817
|
+
export {
|
|
818
|
+
ApiModuleProvider,
|
|
819
|
+
useApi,
|
|
820
|
+
useApiModule,
|
|
821
|
+
useApiRecord,
|
|
822
|
+
useDeepCompareEffect,
|
|
823
|
+
useModuleContext
|
|
824
|
+
};
|