@enfyra/sdk-nuxt 0.3.22 → 0.3.24

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,477 +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>;
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> {
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
-
147
- const loading = computed(() => result.status.value === 'pending');
148
-
149
- return {
150
- ...result,
151
- loading,
152
- } as UseEnfyraApiSSRReturn<T>;
153
- }
154
- const data = ref<T | null>(null);
155
- const error = ref<ApiError | null>(null);
156
- const pending = ref(false);
157
-
158
- const execute = async (executeOpts?: ExecuteOptions) => {
159
- pending.value = true;
160
- error.value = null;
161
-
162
- try {
163
- const config: any = useRuntimeConfig().public.enfyraSDK;
164
- const apiUrl = getAppUrl();
165
- const apiPrefix = config?.apiPrefix;
166
- const basePath = (typeof path === "function" ? path() : path)
167
- .replace(/^\/?api\/?/, "")
168
- .replace(/^\/+/, "");
169
- const finalBody = executeOpts?.body || unref(body);
170
- const finalQuery = executeOpts?.query || unref(query);
171
-
172
- const isBatchOperation =
173
- !opts.disableBatch &&
174
- ((executeOpts?.ids &&
175
- executeOpts.ids.length > 0 &&
176
- (method.toLowerCase() === "patch" ||
177
- method.toLowerCase() === "delete")) ||
178
- (method.toLowerCase() === "post" &&
179
- executeOpts?.files &&
180
- Array.isArray(executeOpts.files) &&
181
- executeOpts.files.length > 0));
182
-
183
- const effectiveBatchSize = isBatchOperation
184
- ? executeOpts?.batchSize ?? batchSize
185
- : undefined;
186
- const effectiveConcurrent = isBatchOperation
187
- ? executeOpts?.concurrent ?? concurrent
188
- : undefined;
189
- const effectiveOnProgress = isBatchOperation
190
- ? executeOpts?.onProgress ?? onProgress
191
- : undefined;
192
-
193
- const buildPath = (...segments: (string | number)[]): string => {
194
- return segments.filter(Boolean).join("/");
195
- };
196
-
197
- const fullBaseURL = normalizeUrl(apiUrl, apiPrefix || ENFYRA_API_PREFIX);
198
-
199
- async function processBatch<T>(
200
- items: any[],
201
- processor: (item: any, index: number) => Promise<T>
202
- ): Promise<T[]> {
203
- const results: T[] = [];
204
- const progressResults: BatchProgress["results"] = [];
205
- const startTime = Date.now();
206
- let completed = 0;
207
- let failed = 0;
208
-
209
- const chunks = effectiveBatchSize
210
- ? Array.from(
211
- { length: Math.ceil(items.length / effectiveBatchSize) },
212
- (_, i) =>
213
- items.slice(
214
- i * effectiveBatchSize,
215
- i * effectiveBatchSize + effectiveBatchSize
216
- )
217
- )
218
- : [items];
219
-
220
- const totalBatches = chunks.length;
221
- let currentBatch = 0;
222
-
223
- const updateProgress = (inProgress: number = 0) => {
224
- if (effectiveOnProgress) {
225
- const elapsed = Date.now() - startTime;
226
- const progress =
227
- items.length > 0
228
- ? Math.round((completed / items.length) * 100)
229
- : 0;
230
- const averageTime = completed > 0 ? elapsed / completed : undefined;
231
- const operationsPerSecond =
232
- completed > 0 ? (completed / elapsed) * 1000 : undefined;
233
- const estimatedTimeRemaining =
234
- averageTime && items.length > completed
235
- ? Math.round(averageTime * (items.length - completed))
236
- : undefined;
237
-
238
- const progressData: BatchProgress = {
239
- progress,
240
- completed,
241
- total: items.length,
242
- failed,
243
- inProgress,
244
- estimatedTimeRemaining,
245
- averageTime,
246
- currentBatch: currentBatch + 1,
247
- totalBatches,
248
- operationsPerSecond,
249
- results: [...progressResults],
250
- };
251
-
252
- effectiveOnProgress(progressData);
253
- }
254
- };
255
-
256
- updateProgress(0);
257
-
258
- if (!effectiveBatchSize && !effectiveConcurrent) {
259
- updateProgress(items.length);
260
-
261
- const promises = items.map(async (item, index) => {
262
- const itemStartTime = Date.now();
263
- try {
264
- const result = await processor(item, index);
265
- const duration = Date.now() - itemStartTime;
266
-
267
- completed++;
268
- progressResults.push({
269
- index,
270
- status: "completed",
271
- result,
272
- duration,
273
- });
274
- updateProgress(items.length - completed);
275
-
276
- return result;
277
- } catch (error) {
278
- const duration = Date.now() - itemStartTime;
279
- failed++;
280
- completed++;
281
-
282
- progressResults.push({
283
- index,
284
- status: "failed",
285
- error: error as ApiError,
286
- duration,
287
- });
288
- updateProgress(items.length - completed);
289
-
290
- throw error;
291
- }
292
- });
293
-
294
- const results = await Promise.all(promises);
295
- updateProgress(0);
296
- return results;
297
- }
298
-
299
- for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
300
- currentBatch = chunkIndex;
301
- const chunk = chunks[chunkIndex];
302
-
303
- if (effectiveConcurrent && chunk.length > effectiveConcurrent) {
304
- for (let i = 0; i < chunk.length; i += effectiveConcurrent) {
305
- const batch = chunk.slice(i, i + effectiveConcurrent);
306
- const baseIndex =
307
- chunkIndex * (effectiveBatchSize || items.length) + i;
308
-
309
- updateProgress(batch.length);
310
-
311
- const batchPromises = batch.map(async (item, batchItemIndex) => {
312
- const globalIndex = baseIndex + batchItemIndex;
313
- const itemStartTime = Date.now();
314
-
315
- try {
316
- const result = await processor(item, globalIndex);
317
- const duration = Date.now() - itemStartTime;
318
-
319
- completed++;
320
- progressResults.push({
321
- index: globalIndex,
322
- status: "completed",
323
- result,
324
- duration,
325
- });
326
- updateProgress(
327
- Math.max(0, batch.length - (batchItemIndex + 1))
328
- );
329
-
330
- return result;
331
- } catch (error) {
332
- const duration = Date.now() - itemStartTime;
333
- failed++;
334
- completed++;
335
-
336
- progressResults.push({
337
- index: globalIndex,
338
- status: "failed",
339
- error: error as ApiError,
340
- duration,
341
- });
342
- updateProgress(
343
- Math.max(0, batch.length - (batchItemIndex + 1))
344
- );
345
-
346
- throw error;
347
- }
348
- });
349
-
350
- const batchResults = await Promise.all(batchPromises);
351
- results.push(...batchResults);
352
- }
353
- } else {
354
- const baseIndex = chunkIndex * (effectiveBatchSize || items.length);
355
-
356
- updateProgress(chunk.length);
357
-
358
- const chunkPromises = chunk.map(async (item, chunkItemIndex) => {
359
- const globalIndex = baseIndex + chunkItemIndex;
360
- const itemStartTime = Date.now();
361
-
362
- try {
363
- const result = await processor(item, globalIndex);
364
- const duration = Date.now() - itemStartTime;
365
-
366
- completed++;
367
- progressResults.push({
368
- index: globalIndex,
369
- status: "completed",
370
- result,
371
- duration,
372
- });
373
- updateProgress(
374
- Math.max(0, chunk.length - (chunkItemIndex + 1))
375
- );
376
-
377
- return result;
378
- } catch (error) {
379
- const duration = Date.now() - itemStartTime;
380
- failed++;
381
- completed++;
382
-
383
- progressResults.push({
384
- index: globalIndex,
385
- status: "failed",
386
- error: error as ApiError,
387
- duration,
388
- });
389
- updateProgress(
390
- Math.max(0, chunk.length - (chunkItemIndex + 1))
391
- );
392
-
393
- throw error;
394
- }
395
- });
396
-
397
- const chunkResults = await Promise.all(chunkPromises);
398
- results.push(...chunkResults);
399
- }
400
- }
401
-
402
- updateProgress(0);
403
- return results;
404
- }
405
-
406
- if (isBatchOperation && executeOpts?.ids && executeOpts.ids.length > 0) {
407
- const responses = await processBatch(
408
- executeOpts.ids,
409
- async (id) => {
410
- const finalPath = buildPath(basePath, id);
411
- return $fetch<T>(finalPath, {
412
- baseURL: fullBaseURL,
413
- method: method as any,
414
- body: finalBody ? toRaw(finalBody) : undefined,
415
- headers: opts.headers,
416
- query: finalQuery,
417
- });
418
- }
419
- );
420
-
421
- data.value = responses as T;
422
- return responses;
423
- }
424
-
425
- if (
426
- isBatchOperation &&
427
- executeOpts?.files &&
428
- Array.isArray(executeOpts.files) &&
429
- executeOpts.files.length > 0
430
- ) {
431
- const responses = await processBatch(
432
- executeOpts.files,
433
- async (fileObj: any) => {
434
- return $fetch<T>(basePath, {
435
- baseURL: fullBaseURL,
436
- method: method as any,
437
- body: fileObj,
438
- headers: opts.headers,
439
- query: finalQuery,
440
- });
441
- }
442
- );
443
-
444
- data.value = responses as T;
445
- return responses;
446
- }
447
-
448
- const finalPath = executeOpts?.id
449
- ? buildPath(basePath, executeOpts.id)
450
- : basePath;
451
-
452
- const response = await $fetch<T>(finalPath, {
453
- baseURL: fullBaseURL,
454
- method: method as any,
455
- body: finalBody ? toRaw(finalBody) : undefined,
456
- headers: opts.headers,
457
- query: finalQuery,
458
- });
459
-
460
- data.value = response;
461
- return response;
462
- } catch (err) {
463
- const apiError = handleError(err, errorContext, onError);
464
- error.value = apiError;
465
- return null;
466
- } finally {
467
- pending.value = false;
468
- }
469
- };
470
-
471
- return {
472
- data,
473
- error,
474
- pending,
475
- execute,
476
- } as UseEnfyraApiClientReturn<T>;
477
- }