@enfyra/sdk-nuxt 0.3.23 → 0.3.25

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.
@@ -1,483 +0,0 @@
1
- import { ref, unref, toRaw, computed } from "vue";
2
- import type {
3
- ApiOptions,
4
- ApiError,
5
- ExecuteOptions,
6
- UseEnfyraApiSSRReturn,
7
- UseEnfyraApiClientReturn,
8
- BatchProgress,
9
- } from "../../types";
10
- import { $fetch } from "../utils/http";
11
- import { getAppUrl, normalizeUrl } from "../utils/url";
12
- import { ENFYRA_API_PREFIX } from "../constants/config";
13
-
14
- import { useRuntimeConfig, useFetch, useRequestHeaders, useNuxtApp } from "#imports";
15
-
16
- function handleError(
17
- error: any,
18
- context?: string,
19
- customHandler?: (error: ApiError, context?: string) => void
20
- ) {
21
- const apiError: ApiError = {
22
- message: error?.message || error?.data?.message || "Request failed",
23
- status: error?.status || error?.response?.status,
24
- data: error?.data || error?.response?.data,
25
- response: error?.response || error,
26
- };
27
-
28
- if (customHandler) {
29
- customHandler(apiError, context);
30
- } else {
31
- console.error(`[Enfyra API Error]`, { error: apiError, context });
32
- }
33
-
34
- return apiError;
35
- }
36
-
37
- export function useEnfyraApi<T = any>(
38
- path: (() => string) | string,
39
- opts: ApiOptions<T> & { ssr: true }
40
- ): UseEnfyraApiSSRReturn<T> | Promise<UseEnfyraApiSSRReturn<T>>;
41
-
42
- export function useEnfyraApi<T = any>(
43
- path: (() => string) | string,
44
- opts?: ApiOptions<T> & { ssr?: false | undefined }
45
- ): UseEnfyraApiClientReturn<T>;
46
-
47
- export function useEnfyraApi<T = any>(
48
- path: (() => string) | string,
49
- opts: ApiOptions<T> = {}
50
- ): UseEnfyraApiSSRReturn<T> | UseEnfyraApiClientReturn<T> | Promise<UseEnfyraApiSSRReturn<T>> {
51
- const { method = "get", body, query, errorContext, onError, ssr, key } = opts;
52
- const batchOptions = opts as any;
53
- const { batchSize, concurrent, onProgress } = batchOptions;
54
-
55
- if (ssr) {
56
- const config = useRuntimeConfig().public.enfyraSDK;
57
- const basePath = (typeof path === "function" ? path() : path)
58
- .replace(/^\/?api\/?/, "")
59
- .replace(/^\/+/, "");
60
-
61
- const appUrl = getAppUrl();
62
- const finalUrl = normalizeUrl(
63
- appUrl,
64
- config?.apiPrefix || ENFYRA_API_PREFIX,
65
- basePath
66
- );
67
-
68
- const clientHeaders = process.client
69
- ? {}
70
- : useRequestHeaders([
71
- "authorization",
72
- "cookie",
73
- "user-agent",
74
- "accept",
75
- "accept-language",
76
- "referer",
77
- ]);
78
-
79
- const serverHeaders = { ...clientHeaders };
80
- delete serverHeaders.connection;
81
- delete serverHeaders["keep-alive"];
82
- delete serverHeaders.host;
83
- delete serverHeaders["content-length"];
84
-
85
- const nuxtApp = useNuxtApp()
86
-
87
- const fetchOptions: any = {
88
- method: method as any,
89
- body: body,
90
- query: query,
91
- headers: {
92
- ...serverHeaders,
93
- ...opts.headers,
94
- },
95
- };
96
-
97
- if (key !== undefined) {
98
- fetchOptions.key = key;
99
- }
100
- if (opts.default !== undefined) {
101
- fetchOptions.default = opts.default;
102
- }
103
- if (opts.server !== undefined) {
104
- fetchOptions.server = opts.server;
105
- }
106
- if (opts.lazy !== undefined) {
107
- fetchOptions.lazy = opts.lazy;
108
- }
109
- if (opts.immediate !== undefined) {
110
- fetchOptions.immediate = opts.immediate;
111
- }
112
- if (opts.transform !== undefined) {
113
- fetchOptions.transform = opts.transform;
114
- }
115
- if (opts.pick !== undefined) {
116
- fetchOptions.pick = opts.pick;
117
- }
118
- if (opts.watch !== undefined) {
119
- fetchOptions.watch = opts.watch;
120
- }
121
- if (opts.deep !== undefined) {
122
- fetchOptions.deep = opts.deep;
123
- }
124
- if (opts.getCachedData !== undefined) {
125
- fetchOptions.getCachedData = opts.getCachedData;
126
- } else {
127
- fetchOptions.getCachedData = (cacheKey: string) => {
128
- return nuxtApp.payload.data[cacheKey] || nuxtApp.static.data[cacheKey]
129
- }
130
- }
131
- if (opts.refresh !== undefined) {
132
- fetchOptions.refresh = opts.refresh;
133
- }
134
- if (opts.refreshInterval !== undefined) {
135
- fetchOptions.refreshInterval = opts.refreshInterval;
136
- }
137
- if (opts.dedupe !== undefined) {
138
- fetchOptions.dedupe = opts.dedupe;
139
- }
140
- if (opts.cache !== undefined) {
141
- fetchOptions.cache = opts.cache;
142
- }
143
-
144
- const result = useFetch<T>(finalUrl, fetchOptions);
145
-
146
- const loading = computed(() => result.status.value === 'pending');
147
-
148
- const returnValue = {
149
- ...result,
150
- loading,
151
- } as UseEnfyraApiSSRReturn<T>;
152
-
153
- // Ở server, return Promise để có thể await (hoặc không)
154
- if (process.server) {
155
- return Promise.resolve(returnValue) as Promise<UseEnfyraApiSSRReturn<T>>;
156
- }
157
-
158
- return returnValue;
159
- }
160
- const data = ref<T | null>(null);
161
- const error = ref<ApiError | null>(null);
162
- const pending = ref(false);
163
-
164
- const execute = async (executeOpts?: ExecuteOptions) => {
165
- pending.value = true;
166
- error.value = null;
167
-
168
- try {
169
- const config: any = useRuntimeConfig().public.enfyraSDK;
170
- const apiUrl = getAppUrl();
171
- const apiPrefix = config?.apiPrefix;
172
- const basePath = (typeof path === "function" ? path() : path)
173
- .replace(/^\/?api\/?/, "")
174
- .replace(/^\/+/, "");
175
- const finalBody = executeOpts?.body || unref(body);
176
- const finalQuery = executeOpts?.query || unref(query);
177
-
178
- const isBatchOperation =
179
- !opts.disableBatch &&
180
- ((executeOpts?.ids &&
181
- executeOpts.ids.length > 0 &&
182
- (method.toLowerCase() === "patch" ||
183
- method.toLowerCase() === "delete")) ||
184
- (method.toLowerCase() === "post" &&
185
- executeOpts?.files &&
186
- Array.isArray(executeOpts.files) &&
187
- executeOpts.files.length > 0));
188
-
189
- const effectiveBatchSize = isBatchOperation
190
- ? executeOpts?.batchSize ?? batchSize
191
- : undefined;
192
- const effectiveConcurrent = isBatchOperation
193
- ? executeOpts?.concurrent ?? concurrent
194
- : undefined;
195
- const effectiveOnProgress = isBatchOperation
196
- ? executeOpts?.onProgress ?? onProgress
197
- : undefined;
198
-
199
- const buildPath = (...segments: (string | number)[]): string => {
200
- return segments.filter(Boolean).join("/");
201
- };
202
-
203
- const fullBaseURL = normalizeUrl(apiUrl, apiPrefix || ENFYRA_API_PREFIX);
204
-
205
- async function processBatch<T>(
206
- items: any[],
207
- processor: (item: any, index: number) => Promise<T>
208
- ): Promise<T[]> {
209
- const results: T[] = [];
210
- const progressResults: BatchProgress["results"] = [];
211
- const startTime = Date.now();
212
- let completed = 0;
213
- let failed = 0;
214
-
215
- const chunks = effectiveBatchSize
216
- ? Array.from(
217
- { length: Math.ceil(items.length / effectiveBatchSize) },
218
- (_, i) =>
219
- items.slice(
220
- i * effectiveBatchSize,
221
- i * effectiveBatchSize + effectiveBatchSize
222
- )
223
- )
224
- : [items];
225
-
226
- const totalBatches = chunks.length;
227
- let currentBatch = 0;
228
-
229
- const updateProgress = (inProgress: number = 0) => {
230
- if (effectiveOnProgress) {
231
- const elapsed = Date.now() - startTime;
232
- const progress =
233
- items.length > 0
234
- ? Math.round((completed / items.length) * 100)
235
- : 0;
236
- const averageTime = completed > 0 ? elapsed / completed : undefined;
237
- const operationsPerSecond =
238
- completed > 0 ? (completed / elapsed) * 1000 : undefined;
239
- const estimatedTimeRemaining =
240
- averageTime && items.length > completed
241
- ? Math.round(averageTime * (items.length - completed))
242
- : undefined;
243
-
244
- const progressData: BatchProgress = {
245
- progress,
246
- completed,
247
- total: items.length,
248
- failed,
249
- inProgress,
250
- estimatedTimeRemaining,
251
- averageTime,
252
- currentBatch: currentBatch + 1,
253
- totalBatches,
254
- operationsPerSecond,
255
- results: [...progressResults],
256
- };
257
-
258
- effectiveOnProgress(progressData);
259
- }
260
- };
261
-
262
- updateProgress(0);
263
-
264
- if (!effectiveBatchSize && !effectiveConcurrent) {
265
- updateProgress(items.length);
266
-
267
- const promises = items.map(async (item, index) => {
268
- const itemStartTime = Date.now();
269
- try {
270
- const result = await processor(item, index);
271
- const duration = Date.now() - itemStartTime;
272
-
273
- completed++;
274
- progressResults.push({
275
- index,
276
- status: "completed",
277
- result,
278
- duration,
279
- });
280
- updateProgress(items.length - completed);
281
-
282
- return result;
283
- } catch (error) {
284
- const duration = Date.now() - itemStartTime;
285
- failed++;
286
- completed++;
287
-
288
- progressResults.push({
289
- index,
290
- status: "failed",
291
- error: error as ApiError,
292
- duration,
293
- });
294
- updateProgress(items.length - completed);
295
-
296
- throw error;
297
- }
298
- });
299
-
300
- const results = await Promise.all(promises);
301
- updateProgress(0);
302
- return results;
303
- }
304
-
305
- for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
306
- currentBatch = chunkIndex;
307
- const chunk = chunks[chunkIndex];
308
-
309
- if (effectiveConcurrent && chunk.length > effectiveConcurrent) {
310
- for (let i = 0; i < chunk.length; i += effectiveConcurrent) {
311
- const batch = chunk.slice(i, i + effectiveConcurrent);
312
- const baseIndex =
313
- chunkIndex * (effectiveBatchSize || items.length) + i;
314
-
315
- updateProgress(batch.length);
316
-
317
- const batchPromises = batch.map(async (item, batchItemIndex) => {
318
- const globalIndex = baseIndex + batchItemIndex;
319
- const itemStartTime = Date.now();
320
-
321
- try {
322
- const result = await processor(item, globalIndex);
323
- const duration = Date.now() - itemStartTime;
324
-
325
- completed++;
326
- progressResults.push({
327
- index: globalIndex,
328
- status: "completed",
329
- result,
330
- duration,
331
- });
332
- updateProgress(
333
- Math.max(0, batch.length - (batchItemIndex + 1))
334
- );
335
-
336
- return result;
337
- } catch (error) {
338
- const duration = Date.now() - itemStartTime;
339
- failed++;
340
- completed++;
341
-
342
- progressResults.push({
343
- index: globalIndex,
344
- status: "failed",
345
- error: error as ApiError,
346
- duration,
347
- });
348
- updateProgress(
349
- Math.max(0, batch.length - (batchItemIndex + 1))
350
- );
351
-
352
- throw error;
353
- }
354
- });
355
-
356
- const batchResults = await Promise.all(batchPromises);
357
- results.push(...batchResults);
358
- }
359
- } else {
360
- const baseIndex = chunkIndex * (effectiveBatchSize || items.length);
361
-
362
- updateProgress(chunk.length);
363
-
364
- const chunkPromises = chunk.map(async (item, chunkItemIndex) => {
365
- const globalIndex = baseIndex + chunkItemIndex;
366
- const itemStartTime = Date.now();
367
-
368
- try {
369
- const result = await processor(item, globalIndex);
370
- const duration = Date.now() - itemStartTime;
371
-
372
- completed++;
373
- progressResults.push({
374
- index: globalIndex,
375
- status: "completed",
376
- result,
377
- duration,
378
- });
379
- updateProgress(
380
- Math.max(0, chunk.length - (chunkItemIndex + 1))
381
- );
382
-
383
- return result;
384
- } catch (error) {
385
- const duration = Date.now() - itemStartTime;
386
- failed++;
387
- completed++;
388
-
389
- progressResults.push({
390
- index: globalIndex,
391
- status: "failed",
392
- error: error as ApiError,
393
- duration,
394
- });
395
- updateProgress(
396
- Math.max(0, chunk.length - (chunkItemIndex + 1))
397
- );
398
-
399
- throw error;
400
- }
401
- });
402
-
403
- const chunkResults = await Promise.all(chunkPromises);
404
- results.push(...chunkResults);
405
- }
406
- }
407
-
408
- updateProgress(0);
409
- return results;
410
- }
411
-
412
- if (isBatchOperation && executeOpts?.ids && executeOpts.ids.length > 0) {
413
- const responses = await processBatch(
414
- executeOpts.ids,
415
- async (id) => {
416
- const finalPath = buildPath(basePath, id);
417
- return $fetch<T>(finalPath, {
418
- baseURL: fullBaseURL,
419
- method: method as any,
420
- body: finalBody ? toRaw(finalBody) : undefined,
421
- headers: opts.headers,
422
- query: finalQuery,
423
- });
424
- }
425
- );
426
-
427
- data.value = responses as T;
428
- return responses;
429
- }
430
-
431
- if (
432
- isBatchOperation &&
433
- executeOpts?.files &&
434
- Array.isArray(executeOpts.files) &&
435
- executeOpts.files.length > 0
436
- ) {
437
- const responses = await processBatch(
438
- executeOpts.files,
439
- async (fileObj: any) => {
440
- return $fetch<T>(basePath, {
441
- baseURL: fullBaseURL,
442
- method: method as any,
443
- body: fileObj,
444
- headers: opts.headers,
445
- query: finalQuery,
446
- });
447
- }
448
- );
449
-
450
- data.value = responses as T;
451
- return responses;
452
- }
453
-
454
- const finalPath = executeOpts?.id
455
- ? buildPath(basePath, executeOpts.id)
456
- : basePath;
457
-
458
- const response = await $fetch<T>(finalPath, {
459
- baseURL: fullBaseURL,
460
- method: method as any,
461
- body: finalBody ? toRaw(finalBody) : undefined,
462
- headers: opts.headers,
463
- query: finalQuery,
464
- });
465
-
466
- data.value = response;
467
- return response;
468
- } catch (err) {
469
- const apiError = handleError(err, errorContext, onError);
470
- error.value = apiError;
471
- return null;
472
- } finally {
473
- pending.value = false;
474
- }
475
- };
476
-
477
- return {
478
- data,
479
- error,
480
- pending,
481
- execute,
482
- } as UseEnfyraApiClientReturn<T>;
483
- }
@@ -1,78 +0,0 @@
1
- export async function $fetch<T = any>(
2
- path: string,
3
- options: {
4
- method?: string;
5
- body?: any;
6
- headers?: Record<string, string>;
7
- query?: Record<string, any>;
8
- baseURL?: string;
9
- } = {}
10
- ): Promise<T> {
11
- const {
12
- method = "GET",
13
- body,
14
- headers: optionHeaders = {},
15
- query = {},
16
- baseURL,
17
- } = options;
18
- if (!baseURL) {
19
- throw new Error('baseURL is required for $fetch');
20
- }
21
-
22
- const url = new URL(
23
- path.startsWith("/") ? path.slice(1) : path,
24
- baseURL.endsWith("/") ? baseURL : `${baseURL}/`
25
- );
26
-
27
- Object.entries(query).forEach(([key, value]) => {
28
- if (value !== undefined && value !== null) {
29
- if (typeof value === 'object') {
30
- url.searchParams.append(key, JSON.stringify(value));
31
- } else {
32
- url.searchParams.append(key, String(value));
33
- }
34
- }
35
- });
36
-
37
- const headers: Record<string, string> = {
38
- "Content-Type": "application/json",
39
- ...optionHeaders,
40
- };
41
-
42
- const fetchOptions: RequestInit = {
43
- method: method.toUpperCase(),
44
- headers,
45
- };
46
-
47
- if (body && method.toUpperCase() !== "GET") {
48
- if (body instanceof FormData) {
49
- delete headers["Content-Type"]; // Let browser set boundary for FormData
50
- fetchOptions.body = body;
51
- } else {
52
- fetchOptions.body = JSON.stringify(body);
53
- }
54
- }
55
-
56
- try {
57
- const response = await fetch(url.toString(), fetchOptions);
58
-
59
- if (!response.ok) {
60
- let errorData;
61
- try {
62
- errorData = await response.json();
63
- } catch {
64
- errorData = { message: response.statusText };
65
- }
66
- throw { response: { data: errorData } };
67
- }
68
-
69
- const contentType = response.headers.get("content-type");
70
- if (contentType?.includes("application/json")) {
71
- return await response.json();
72
- } else {
73
- return (await response.text()) as T;
74
- }
75
- } catch (error) {
76
- throw error;
77
- }
78
- }