@jwork-space/strapi-sdk 1.0.1

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.mjs ADDED
@@ -0,0 +1,993 @@
1
+ // src/types.ts
2
+ var publicRoutes = [
3
+ "auth/local",
4
+ "auth/local/register",
5
+ "recovery-codes"
6
+ ];
7
+ function isObject(value) {
8
+ return Object.prototype.toString.call(value) === "[object Object]";
9
+ }
10
+ function isDefined(value) {
11
+ return value !== void 0 && value !== null;
12
+ }
13
+ function getKeyByValue(object, value) {
14
+ return Object.keys(object).find(
15
+ (key) => object[key] === value
16
+ );
17
+ }
18
+ function isEmptyObject(object) {
19
+ return Object.entries(object).length === 0;
20
+ }
21
+ function isPlainObject(value) {
22
+ return Object.prototype.toString.call(value) === "[object Object]";
23
+ }
24
+ var generateUID = (length) => {
25
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
26
+ let result = "";
27
+ for (let i = 0; i < length; i++) {
28
+ result += characters.charAt(Math.floor(Math.random() * characters.length));
29
+ }
30
+ return result;
31
+ };
32
+ var generateFakeFirebaseUID = () => generateUID(10);
33
+
34
+ // src/base-api-helper.ts
35
+ var HelperStrapiAPI = class {
36
+ getSortingLocal(values, defaultSorter = "name") {
37
+ if (!values?.order || !values?.field) return defaultSorter;
38
+ const map = {
39
+ ascend: "asc",
40
+ descend: "desc"
41
+ };
42
+ const field = values.field.toString();
43
+ return `${field}:${map[values.order]}`;
44
+ }
45
+ getPayload(object) {
46
+ const formData = new FormData();
47
+ const data = { data: {} };
48
+ Object.keys(object).forEach((proprerty) => {
49
+ if (object[proprerty] instanceof File) {
50
+ formData.append(`files.${proprerty}`, object[proprerty]);
51
+ } else {
52
+ const value = object[proprerty];
53
+ data.data[proprerty] = value;
54
+ }
55
+ });
56
+ if (this.isFormDataEmpty(formData)) return data;
57
+ formData.append("data", JSON.stringify({ data: data.data }));
58
+ return formData;
59
+ }
60
+ isFormDataEmpty(formData) {
61
+ for (const item of formData.entries()) if (item) return false;
62
+ return true;
63
+ }
64
+ };
65
+ var helperStrapiAPI = new HelperStrapiAPI();
66
+
67
+ // src/http-layer.ts
68
+ import axios from "axios";
69
+ import dayjs from "dayjs";
70
+ import qs from "qs";
71
+ var LocalStoreManager = class {
72
+ constructor(tokenKey = "jwt") {
73
+ this.tokenKey = tokenKey;
74
+ }
75
+ getLocalStorageKey(key) {
76
+ return localStorage.getItem(key);
77
+ }
78
+ removeStorageKey(key) {
79
+ localStorage.removeItem(key);
80
+ }
81
+ setLocalStorage(key, value) {
82
+ const existValue = this.getLocalStorageKey(key);
83
+ if (existValue && existValue !== value) {
84
+ this.removeStorageKey(key);
85
+ }
86
+ localStorage.setItem(key, value);
87
+ }
88
+ getToken() {
89
+ return this.getLocalStorageKey(this.tokenKey);
90
+ }
91
+ setToken(token) {
92
+ const existToken = this.getToken();
93
+ if (existToken && existToken !== token) {
94
+ this.removeStorageKey(this.tokenKey);
95
+ }
96
+ this.setLocalStorage(this.tokenKey, token);
97
+ }
98
+ removeToken() {
99
+ this.removeStorageKey(this.tokenKey);
100
+ }
101
+ };
102
+ var HttpLayer = class {
103
+ constructor(tokenKey) {
104
+ this.tokenManager = new LocalStoreManager(tokenKey);
105
+ }
106
+ mergeHeaders(uri, options) {
107
+ const baseHeaders = this.getHeaders(options, uri);
108
+ return {
109
+ ...baseHeaders,
110
+ ...options?.headers
111
+ };
112
+ }
113
+ getHeaders({ auth = true, headers }, uri) {
114
+ const localHeaders = new axios.AxiosHeaders({
115
+ ...headers
116
+ });
117
+ if (auth) {
118
+ if (uri.includes("strapi/") && publicRoutes.includes(uri.slice(7)))
119
+ return localHeaders;
120
+ localHeaders.Authorization = `Bearer ${this.tokenManager.getToken()}`;
121
+ }
122
+ return localHeaders;
123
+ }
124
+ async makeRequest(uri, method, opt = {}) {
125
+ const headers = this.getHeaders(opt, uri);
126
+ const httpMethod = axios[method];
127
+ const config = { headers };
128
+ if (opt.query) {
129
+ config.params = { ...opt.query, ...opt.query.extraQuery };
130
+ delete config.params.extraQuery;
131
+ config.paramsSerializer = (query) => qs.stringify(query, { encodeValuesOnly: true });
132
+ }
133
+ if (["get", "delete"].includes(method)) {
134
+ const { data: data2 } = await httpMethod(uri, config);
135
+ return data2;
136
+ }
137
+ const { data } = await httpMethod(uri, opt.body, config);
138
+ return data;
139
+ }
140
+ executeRequest(uri, method, opt = {}) {
141
+ const httpMethod = axios[method];
142
+ const config = {
143
+ headers: this.mergeHeaders(uri, opt)
144
+ };
145
+ if (opt.query) {
146
+ config.params = { ...opt.query, ...opt.query.extraQuery };
147
+ delete config.params.extraQuery;
148
+ config.paramsSerializer = (query) => qs.stringify(query, { encodeValuesOnly: true });
149
+ }
150
+ if (["get", "delete"].includes(method)) return httpMethod(uri, config);
151
+ return httpMethod(uri, opt.body, config);
152
+ }
153
+ async makeRequestV2(uri, method, opt = {}) {
154
+ const headers = this.getHeaders(opt, uri);
155
+ const httpMethod = axios[method];
156
+ const config = { headers };
157
+ if (opt.query) {
158
+ config.params = { ...opt.query, ...opt.query.extraQuery };
159
+ delete config.params.extraQuery;
160
+ config.paramsSerializer = (query) => qs.stringify(query, { encodeValuesOnly: true });
161
+ }
162
+ if (["get", "delete"].includes(method))
163
+ return await httpMethod(uri, config);
164
+ return await httpMethod(uri, opt.body, config);
165
+ }
166
+ getFileName(contentDisposition) {
167
+ let filename = "file";
168
+ if (contentDisposition && contentDisposition.includes("filename="))
169
+ filename = contentDisposition.split("filename=")[1].replaceAll(/["']/g, "");
170
+ return filename;
171
+ }
172
+ async getFileFromAPI({
173
+ uri,
174
+ method,
175
+ opt = {},
176
+ fileName
177
+ }) {
178
+ const headers = this.getHeaders(opt, uri);
179
+ const config = {
180
+ headers,
181
+ responseType: "blob",
182
+ params: opt.query,
183
+ data: opt.body
184
+ };
185
+ const response = await axios[method](uri, opt.body, config);
186
+ const blob = new Blob([response.data], {
187
+ type: response.headers["content-type"] || "application/octet-stream"
188
+ });
189
+ const url = window.URL.createObjectURL(blob);
190
+ const link = document.createElement("a");
191
+ link.href = url;
192
+ link.download = fileName ?? this.getFileName(response.headers["content-disposition"]) ?? dayjs().format("DDMMYYYYhhmmss");
193
+ document.body.append(link);
194
+ link.click();
195
+ link.remove();
196
+ window.URL.revokeObjectURL(url);
197
+ }
198
+ getCall(uri, opt = {}) {
199
+ return this.makeRequest(uri, "get", opt);
200
+ }
201
+ postCall(uri, opt = {}) {
202
+ return this.makeRequest(uri, "post", opt);
203
+ }
204
+ putCall(uri, opt = {}) {
205
+ return this.makeRequest(uri, "put", opt);
206
+ }
207
+ deleteCall(uri, opt = {}) {
208
+ return this.makeRequest(uri, "delete", opt);
209
+ }
210
+ };
211
+
212
+ // src/base-api.ts
213
+ var buildPath = (...segments) => `/${segments.filter(Boolean).map((s) => s.replaceAll(/^\/|\/$/g, "")).join("/")}`;
214
+ var BaseAPI = class extends HttpLayer {
215
+ constructor(resource, prefix, tokenKey, baseURL) {
216
+ super(tokenKey);
217
+ this.resource = resource;
218
+ this.prefix = prefix;
219
+ this.tokenKey = tokenKey;
220
+ this.baseURL = baseURL;
221
+ this.buildPath = buildPath;
222
+ this.normalizePath = (value) => value.replace(/\/+$/, "");
223
+ const paths = [prefix, resource];
224
+ const pathURL = this.normalizePath(this.buildPath(...paths));
225
+ this.endpoint = `${baseURL}${pathURL}`;
226
+ }
227
+ };
228
+
229
+ // src/base-api-uploader.ts
230
+ var BaseUploaderAPI = class extends HttpLayer {
231
+ constructor(resource, prefix, tokenKey, baseURL) {
232
+ super(tokenKey);
233
+ this.resource = resource;
234
+ this.prefix = prefix;
235
+ this.tokenKey = tokenKey;
236
+ this.baseURL = baseURL;
237
+ this.buildPath = buildPath;
238
+ this.normalizePath = (value) => value.replace(/\/+$/, "");
239
+ const paths = [prefix, resource];
240
+ const pathURL = this.normalizePath(this.buildPath(...paths));
241
+ this.endpoint = `${baseURL}${pathURL}`;
242
+ }
243
+ };
244
+
245
+ // src/strapi-sdk.ts
246
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
247
+ var StrapiSDK = class extends BaseAPI {
248
+ constructor(resource, config) {
249
+ const tokenKey = config?.tokenKey ?? "jwt";
250
+ const baseURL = config?.baseURL ?? "";
251
+ const prefix = config?.prefix ?? "";
252
+ super(resource, prefix, config?.tokenKey, baseURL);
253
+ this.exist = async (opt) => {
254
+ const uri = opt?.url ?? this.endpoint;
255
+ const { data } = await this.getCall(
256
+ uri,
257
+ this.getRequestParams({
258
+ ...opt,
259
+ pagination: {
260
+ page: 1,
261
+ pageSize: 1
262
+ }
263
+ })
264
+ );
265
+ const list = data;
266
+ return list.length > 0;
267
+ };
268
+ this.listAll = async (opt) => {
269
+ const uri = opt?.url ?? this.endpoint;
270
+ const { data, meta } = await this.getCall(
271
+ uri,
272
+ this.getRequestParams(opt)
273
+ );
274
+ return {
275
+ data,
276
+ pagination: {
277
+ ...meta.pagination,
278
+ currentTotal: data.length
279
+ }
280
+ };
281
+ };
282
+ this.getAllData = async (options) => {
283
+ const list = [];
284
+ const opt = {
285
+ sort: "id:asc",
286
+ pagination: {
287
+ page: 1,
288
+ pageSize: 100
289
+ },
290
+ ...options
291
+ };
292
+ let currentPage = opt.pagination.page;
293
+ let pageCount = 1;
294
+ while (currentPage <= pageCount) {
295
+ const { data, pagination } = await this.listAll(opt);
296
+ list.push(...data);
297
+ pageCount = pagination.pageCount;
298
+ currentPage += 1;
299
+ opt.pagination.page = currentPage;
300
+ }
301
+ return {
302
+ data: list,
303
+ opt,
304
+ paging: { pageCount },
305
+ pagination: opt.pagination
306
+ };
307
+ };
308
+ this.show = async (id, opt) => {
309
+ const uri = `${opt?.url ?? this.endpoint}/${id}`;
310
+ const { data } = await this.getCall(
311
+ uri,
312
+ this.getRequestParams(opt)
313
+ );
314
+ return data;
315
+ };
316
+ this.patchRequest = (options, id, opt) => {
317
+ if (id) {
318
+ return {
319
+ uri: `${opt?.url ?? this.endpoint}/${id}`
320
+ };
321
+ }
322
+ return {
323
+ uri: opt?.url ?? this.endpoint,
324
+ options: ["id", ...options.exclude ?? []]
325
+ };
326
+ };
327
+ this.buildPayloadToStore = (model, id) => {
328
+ const isNew = !id || id === 0;
329
+ const keyUID = this.config.onCreate.keyUID ?? "strapiUID";
330
+ const createUID = this.config.onCreate.generateUID ?? true;
331
+ const isAllowedCreateUID = isNew && createUID;
332
+ model = {
333
+ ...model,
334
+ ...!model.createdAtFirebase && isNew && { createdAtFirebase: /* @__PURE__ */ new Date() },
335
+ ...!model.strapiUID && isAllowedCreateUID && { [keyUID]: generateFakeFirebaseUID() }
336
+ };
337
+ if (id) {
338
+ delete model.createdAtFirebase;
339
+ delete model[keyUID];
340
+ }
341
+ return model;
342
+ };
343
+ this.store = async (model, id, opt, serializeOptions) => {
344
+ model = this.buildPayloadToStore(model, id);
345
+ if (opt?.forceUpdateStrapiUID) {
346
+ model = {
347
+ ...model,
348
+ [this.config.onCreate.keyUID ?? "strapiUID"]: generateFakeFirebaseUID()
349
+ };
350
+ }
351
+ const options = { ...serializeOptions };
352
+ const { uri, options: customOptions } = this.patchRequest(options, id, opt);
353
+ options.exclude = customOptions;
354
+ const { id: modelId, ...payload } = model;
355
+ const data = this.getRequestParams({
356
+ ...opt,
357
+ pagination: {
358
+ page: 1,
359
+ pageSize: 1
360
+ }
361
+ });
362
+ data.body = this.normalizeBody(
363
+ payload,
364
+ id ? "update" : "save",
365
+ opt ?? {},
366
+ options
367
+ );
368
+ if (id) {
369
+ const response = await this.putCall(uri, data);
370
+ return response.data;
371
+ } else {
372
+ const { data: dataResponse } = await this.postCall(
373
+ uri,
374
+ data
375
+ );
376
+ return dataResponse;
377
+ }
378
+ };
379
+ this.save = async (model, opt, serializeOptions) => {
380
+ if (typeof model.id === "number" && model.id >= 0) {
381
+ const { id, ...payload } = model;
382
+ return await this.store(payload, 0, opt, serializeOptions);
383
+ }
384
+ return await this.store(model, 0, opt, serializeOptions);
385
+ };
386
+ this.update = async (id, model, opt, serializeOptions) => {
387
+ return await this.store(model, id, opt, serializeOptions);
388
+ };
389
+ this.updateOne = async (model, opt, serializeOptions, _createRelations) => {
390
+ const { id, ...payload } = model;
391
+ const { data } = await this.makeRequestV2(
392
+ `${opt?.url ?? this.endpoint}`,
393
+ "put",
394
+ {
395
+ body: this.normalizeBody(
396
+ payload,
397
+ "update",
398
+ opt ?? {},
399
+ serializeOptions
400
+ ),
401
+ ...this.getRequestParams({
402
+ ...opt,
403
+ pagination: {
404
+ page: 1,
405
+ pageSize: 1
406
+ }
407
+ })
408
+ }
409
+ );
410
+ return data;
411
+ };
412
+ this.destroy = async (id, opt) => {
413
+ const uri = `${opt?.url ?? this.endpoint}/${id}`;
414
+ await this.deleteCall(
415
+ uri,
416
+ this.getRequestParams({
417
+ ...opt,
418
+ pagination: {
419
+ page: 1,
420
+ pageSize: 1
421
+ }
422
+ })
423
+ );
424
+ return true;
425
+ };
426
+ this.findOne = async (opt) => {
427
+ const uri = opt?.url ?? this.endpoint;
428
+ if (opt) delete opt.sort;
429
+ const method = opt?.method ?? "get";
430
+ opt = {
431
+ ...opt,
432
+ pagination: {
433
+ page: 1,
434
+ pageSize: 1
435
+ }
436
+ };
437
+ const { data } = method === "get" ? await this.getCall(uri, this.getRequestParams(opt)) : await this.postCall(uri, this.getRequestParams(opt));
438
+ return data.length > 0 ? data[0] : null;
439
+ };
440
+ this.findById = async (id, opt) => {
441
+ const uri = `${opt?.url ?? this.endpoint}/${id}`;
442
+ if (opt) delete opt.sort;
443
+ const { data } = opt?.method === "get" ? await this.getCall(uri, this.getRequestParams(opt)) : await this.postCall(uri, this.getRequestParams(opt));
444
+ return data;
445
+ };
446
+ this.useListAll = (opt) => {
447
+ return useQuery({
448
+ queryKey: [this.endpoint, "listAll", opt],
449
+ queryFn: async () => {
450
+ return await this.listAll(opt);
451
+ }
452
+ });
453
+ };
454
+ this.useListAllCustom = (opt, enabled = true) => {
455
+ return useQuery({
456
+ queryKey: [this.endpoint, "listAll", opt],
457
+ queryFn: async () => {
458
+ try {
459
+ return await this.listAll(opt);
460
+ } catch (error) {
461
+ console.error("Error al obtener los datos:", error);
462
+ return {
463
+ data: [],
464
+ pagination: {
465
+ page: 0,
466
+ pageCount: 0,
467
+ pageSize: 0,
468
+ total: 0,
469
+ currentTotal: 0
470
+ }
471
+ };
472
+ }
473
+ },
474
+ enabled
475
+ });
476
+ };
477
+ this.useGetAllData = (opt) => {
478
+ return useQuery({
479
+ queryKey: [this.endpoint, "getAllData", opt],
480
+ queryFn: async () => {
481
+ return await this.getAllData(opt);
482
+ }
483
+ });
484
+ };
485
+ this.useGetAllDataCustom = (opt, enabled = true) => {
486
+ return useQuery({
487
+ queryKey: [this.endpoint, "listAll", opt],
488
+ queryFn: async () => {
489
+ try {
490
+ const result = await this.getAllData(opt);
491
+ return result.data ?? [];
492
+ } catch (error) {
493
+ console.error("Error al obtener los datos:", error);
494
+ return [];
495
+ }
496
+ },
497
+ enabled
498
+ });
499
+ };
500
+ //in process
501
+ this.useExistEntity = (opt) => {
502
+ return useQuery({
503
+ queryKey: [this.endpoint, "exist", opt],
504
+ queryFn: async () => await this.exist(opt),
505
+ enabled: false
506
+ });
507
+ };
508
+ this.useShow = (id, opt) => {
509
+ return useQuery({
510
+ queryKey: [this.endpoint, "show", id],
511
+ queryFn: async () => await this.show(id, opt),
512
+ enabled: !!id
513
+ });
514
+ };
515
+ this.useFindOneAsync = (opt, enabled) => {
516
+ return useQuery({
517
+ queryKey: [this.endpoint, "findOne"],
518
+ queryFn: async () => await this.findOne(opt),
519
+ enabled
520
+ });
521
+ };
522
+ this.useFindOne = (opt) => {
523
+ return useQuery({
524
+ queryKey: [this.endpoint, "findOne", opt],
525
+ queryFn: async () => {
526
+ return await this.findOne(opt);
527
+ }
528
+ });
529
+ };
530
+ this.useFindById = (id, opt) => {
531
+ return useQuery({
532
+ queryKey: [this.endpoint, "findOne", id, opt],
533
+ queryFn: async () => {
534
+ return await this.findById(id, opt);
535
+ }
536
+ });
537
+ };
538
+ this.useStore = (opt) => {
539
+ const queryClient = useQueryClient();
540
+ const keys = this.getInvalidateKeys("update", opt);
541
+ return useMutation({
542
+ mutationFn: async ({
543
+ data,
544
+ id,
545
+ requestOptions,
546
+ serializeOptions
547
+ }) => await this.store(data, id, requestOptions, serializeOptions),
548
+ onSuccess: (data) => {
549
+ for (const key of keys) {
550
+ queryClient.invalidateQueries({
551
+ queryKey: Array.isArray(key) ? key : [key]
552
+ });
553
+ }
554
+ opt?.onSuccess?.(data);
555
+ },
556
+ onError: (error) => opt?.onError?.(error)
557
+ });
558
+ };
559
+ this.useSave = (opt) => {
560
+ const queryClient = useQueryClient();
561
+ const keys = this.getInvalidateKeys("save", opt);
562
+ return useMutation({
563
+ mutationFn: async ({
564
+ data,
565
+ requestOptions,
566
+ serializeOptions
567
+ }) => {
568
+ return await this.store(
569
+ data,
570
+ void 0,
571
+ requestOptions,
572
+ serializeOptions
573
+ );
574
+ },
575
+ onSuccess: (data) => {
576
+ for (const key of keys) {
577
+ queryClient.invalidateQueries({
578
+ queryKey: Array.isArray(key) ? key : [key]
579
+ });
580
+ }
581
+ opt?.onSuccess?.(data);
582
+ return data;
583
+ },
584
+ onError: (error) => opt?.onError?.(error)
585
+ });
586
+ };
587
+ this.useUpdate = (opt) => {
588
+ const queryClient = useQueryClient();
589
+ const keys = this.getInvalidateKeys("update", opt);
590
+ return useMutation({
591
+ mutationFn: async ({
592
+ data,
593
+ id,
594
+ requestOptions,
595
+ serializeOptions
596
+ }) => await this.store(data, id, requestOptions, serializeOptions),
597
+ onSuccess: (data) => {
598
+ for (const key of keys) {
599
+ queryClient.invalidateQueries({
600
+ queryKey: Array.isArray(key) ? key : [key]
601
+ });
602
+ }
603
+ opt?.onSuccess?.(data);
604
+ },
605
+ onError: (error) => opt?.onError?.(error)
606
+ });
607
+ };
608
+ this.useUpsert = (opt) => {
609
+ const queryClient = useQueryClient();
610
+ const keys = this.getInvalidateKeys("update", opt);
611
+ return useMutation({
612
+ mutationFn: async ({
613
+ data,
614
+ id,
615
+ requestOptions,
616
+ serializeOptions
617
+ }) => await this.store(data, id, requestOptions, serializeOptions),
618
+ onSuccess: (data) => {
619
+ for (const key of keys) {
620
+ queryClient.invalidateQueries({
621
+ queryKey: Array.isArray(key) ? key : [key]
622
+ });
623
+ }
624
+ opt?.onSuccess?.(data);
625
+ },
626
+ onError: (error) => opt?.onError?.(error)
627
+ });
628
+ };
629
+ this.useDestroy = (opt) => {
630
+ const queryClient = useQueryClient();
631
+ return useMutation({
632
+ mutationFn: async (id) => await this.destroy(id),
633
+ onSuccess: () => {
634
+ queryClient.invalidateQueries({ queryKey: [this.endpoint] });
635
+ opt?.onSuccess?.();
636
+ },
637
+ onError: (error) => opt?.onError?.(error)
638
+ });
639
+ };
640
+ this.finOneEntity = async (opt) => {
641
+ const uri = opt?.url ?? this.endpoint;
642
+ opt = {
643
+ ...opt,
644
+ pagination: { page: 1, pageSize: 2 }
645
+ };
646
+ const { data } = await this.getCall(
647
+ uri,
648
+ this.getRequestParams({
649
+ ...opt,
650
+ pagination: {
651
+ page: 1,
652
+ pageSize: 2
653
+ }
654
+ })
655
+ );
656
+ const list = data;
657
+ return list.length > 0 ? list[0] : null;
658
+ };
659
+ this.config = {
660
+ onCreate: {
661
+ generateUID: config?.onCreate?.generateUID ?? true,
662
+ keyUID: config?.onCreate?.keyUID ?? "strapiUID"
663
+ },
664
+ defaultQueriesInvalidations: config?.defaultQueriesInvalidations ?? {},
665
+ prefix,
666
+ tokenKey,
667
+ wrapBodyInData: config?.wrapBodyInData ?? true,
668
+ transformResponse: config?.transformResponse ?? true,
669
+ pageSize: config?.pageSize ?? 15,
670
+ baseURL
671
+ };
672
+ }
673
+ getQueryParams(opt) {
674
+ const query = {
675
+ sort: opt?.sort || "id:asc",
676
+ pagination: {
677
+ page: opt?.pagination?.page || 1,
678
+ pageSize: opt?.pagination?.pageSize || this.config.pageSize
679
+ }
680
+ };
681
+ if (opt?.populate) query.populate = opt.populate;
682
+ query.filters = {
683
+ ...query.filters,
684
+ ...opt?.filters
685
+ };
686
+ if (opt?.fields) query.fields = opt.fields;
687
+ return query;
688
+ }
689
+ normalizeBody(model, action, { multipart, transformModel }, serializeOptions) {
690
+ if (multipart) return multipart(model, action);
691
+ const data = transformModel ? transformModel(model, action) : model;
692
+ const body = this.serialize(data, serializeOptions);
693
+ return this.config.wrapBodyInData ? { data: body } : body;
694
+ }
695
+ getRequestParams(opt) {
696
+ const options = {
697
+ auth: opt?.auth ?? true,
698
+ query: this.getQueryParams(opt)
699
+ };
700
+ return options;
701
+ }
702
+ async requestExecutor({ uri, data }) {
703
+ return await this.postCall(uri, data);
704
+ }
705
+ serialize(model, options) {
706
+ const payload = {};
707
+ const opt = this.buildOptions(options);
708
+ for (const [key, value] of Object.entries(model)) {
709
+ if (this.shouldSkipKey(key, value, opt)) continue;
710
+ payload[key] = this.transformValue(key, value, opt);
711
+ }
712
+ return payload;
713
+ }
714
+ shouldSkipKey(key, value, opt) {
715
+ return opt.exclude.includes(key) || !opt.preserveBlank && (!isDefined(value) || value === "");
716
+ }
717
+ transformValue(key, value, opt) {
718
+ if (Array.isArray(value)) {
719
+ return this.serializeArray(value, key, opt);
720
+ }
721
+ if (isObject(value)) {
722
+ if (value.id === 0) delete value.id;
723
+ return opt.onlyIdForRelations && !opt.preserveRelations.includes(key) ? value.id : value;
724
+ }
725
+ return value;
726
+ }
727
+ // Utils
728
+ buildOptions(options) {
729
+ return {
730
+ preserveBlank: options?.preserveBlank ?? false,
731
+ onlyIdForRelations: options?.onlyIdForRelations ?? false,
732
+ preserveRelations: options?.preserveRelations ?? [],
733
+ exclude: options?.exclude ?? [],
734
+ removeEmptyArrays: options?.removeEmptyArrays ?? true,
735
+ removeEmptyObjects: options?.removeEmptyObjects ?? true
736
+ };
737
+ }
738
+ serializeArray(value, _key, opt) {
739
+ if (value.every((item) => isObject(item))) {
740
+ return value.map((item) => {
741
+ return opt.onlyIdForRelations ? item.id : item;
742
+ });
743
+ }
744
+ if (!opt.removeEmptyArrays || value.length > 0) {
745
+ return value;
746
+ }
747
+ }
748
+ getInvalidateKeys(method, opt) {
749
+ const defaultKeys = this.defaultInvalidateKeys?.[method] ?? [[]];
750
+ const extraKeys = opt?.invalidateKeys ?? [];
751
+ return [...defaultKeys, ...extraKeys, [this.endpoint]];
752
+ }
753
+ async findOrCreate(data, optFind, optPayload, serializeOptionsPayload) {
754
+ const exist = await this.finOneEntity(optFind);
755
+ if (exist) return exist;
756
+ return await this.store(data, 0, optPayload, serializeOptionsPayload);
757
+ }
758
+ async findAndUpdate(data, optFilter, optPayload, serializeOptionsPayload) {
759
+ const exist = await this.finOneEntity(optFilter);
760
+ if (exist) {
761
+ return await this.store(
762
+ data,
763
+ exist.id,
764
+ optPayload,
765
+ serializeOptionsPayload
766
+ );
767
+ }
768
+ }
769
+ async upsert(data, opt, serializeOptions) {
770
+ const exist = await this.finOneEntity(opt);
771
+ if (exist) {
772
+ return await this.store(data, exist.id, opt, serializeOptions);
773
+ }
774
+ return await this.store(data, 0, opt, serializeOptions);
775
+ }
776
+ };
777
+
778
+ // src/strapi-uploader.sdk.ts
779
+ import { useMutation as useMutation2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
780
+ var StrapiUploaderSDK = class extends BaseUploaderAPI {
781
+ constructor(resource, config) {
782
+ const tokenKey = config?.tokenKey ?? "jwt";
783
+ const baseURL = config?.baseURL ?? "";
784
+ const prefix = config?.prefix ?? "";
785
+ super(resource, prefix, config?.tokenKey, baseURL);
786
+ this.uploadStrapiFile = async (resource, opt) => {
787
+ const uri = opt?.url ?? `${this.baseURL}/upload`;
788
+ const data = this.getRequestParams(opt);
789
+ const formData = new FormData();
790
+ const isMultiple = Array.isArray(resource);
791
+ const files = isMultiple ? resource : [resource];
792
+ files.forEach((file) => {
793
+ formData.append("files", file);
794
+ });
795
+ const fileInfos = files.map((file) => {
796
+ const fileName = file.name || "uploaded_file";
797
+ const info = { name: fileName };
798
+ if (opt?.folder) {
799
+ info.folder = opt.folder;
800
+ }
801
+ return info;
802
+ });
803
+ const fileInfoPayload = fileInfos.length === 1 ? fileInfos[0] : fileInfos;
804
+ formData.append("fileInfo", JSON.stringify(fileInfoPayload));
805
+ data.body = formData;
806
+ try {
807
+ const dataResponse = await this.postCall(
808
+ uri,
809
+ data
810
+ );
811
+ if (!dataResponse || !Array.isArray(dataResponse)) {
812
+ throw new Error("Respuesta inesperada del servidor");
813
+ }
814
+ return dataResponse;
815
+ } catch (error) {
816
+ console.error("\u274C Error al subir archivo:", error);
817
+ throw error;
818
+ }
819
+ };
820
+ this.downloadFile = async (data, fileName, optRequest) => {
821
+ const uri = `${this.baseURL}/data-log/export-to-excel`;
822
+ const method = "post";
823
+ const opt = {
824
+ body: { data },
825
+ responseType: "blob",
826
+ ...optRequest
827
+ };
828
+ await this.getFileFromAPI({ uri, method, opt, fileName });
829
+ };
830
+ this.uploadStrapiImages = async (fileList, oldImages = []) => {
831
+ const oldFiles = new Set(
832
+ fileList.filter((f) => !f.originFileObj).map((item) => Number(item.uid))
833
+ );
834
+ const filesToUpload = fileList.map((f) => f.originFileObj).filter((f) => !!f);
835
+ const imagesUpdates = oldImages.filter((image) => oldFiles.has(image.id));
836
+ if (filesToUpload.length === 0) {
837
+ return imagesUpdates;
838
+ }
839
+ try {
840
+ const newsImages = await this.uploadStrapiFile(filesToUpload);
841
+ return [...imagesUpdates, ...newsImages];
842
+ } catch (error) {
843
+ console.error("Error al subir archivos:", error);
844
+ return [];
845
+ }
846
+ };
847
+ this.useUploadImages = (opt) => {
848
+ return useMutation2({
849
+ mutationFn: async ({
850
+ fileList,
851
+ oldImages = []
852
+ }) => {
853
+ const oldFiles = new Set(
854
+ fileList.filter((f) => !f.originFileObj).map((item) => Number(item.uid))
855
+ );
856
+ const filesToUpload = fileList.map((f) => f.originFileObj).filter((f) => !!f);
857
+ const imagesUpdates = oldImages?.filter(
858
+ (image) => oldFiles.has(image.id)
859
+ );
860
+ if (filesToUpload.length === 0) {
861
+ return imagesUpdates;
862
+ }
863
+ try {
864
+ const newsImages = await this.uploadStrapiFile(filesToUpload);
865
+ return [...imagesUpdates, ...newsImages];
866
+ } catch (error) {
867
+ console.error("Error al subir archivos:", error);
868
+ return [];
869
+ }
870
+ },
871
+ onSuccess: (data) => {
872
+ opt?.onSuccess?.(data);
873
+ },
874
+ onError: (error) => opt?.onError?.(error)
875
+ });
876
+ };
877
+ this.useUploadImagesCreate = (opt) => {
878
+ const queryClient = useQueryClient2();
879
+ const keys = this.getInvalidateKeys("save", opt);
880
+ return useMutation2({
881
+ mutationFn: async ({ fileList }) => {
882
+ const filesToUpload = fileList.map((f) => f.originFileObj).filter((f) => !!f);
883
+ try {
884
+ if (filesToUpload.length === 0) return [];
885
+ return await this.uploadStrapiFile(filesToUpload);
886
+ } catch (error) {
887
+ console.error("Error al subir archivos:", error);
888
+ return [];
889
+ }
890
+ },
891
+ onSuccess: (data) => {
892
+ for (const key of keys) {
893
+ queryClient.invalidateQueries({
894
+ queryKey: Array.isArray(key) ? key : [key]
895
+ });
896
+ }
897
+ opt?.onSuccess?.(data);
898
+ },
899
+ onError: (error) => opt?.onError?.(error)
900
+ });
901
+ };
902
+ this.uploadMergerImages = async (fileList, oldImages = []) => {
903
+ const oldFiles = new Set(
904
+ fileList.filter((f) => !f.originFileObj).map((item) => Number(item.uid))
905
+ );
906
+ const filesToUpload = fileList.map((f) => f.originFileObj).filter((f) => !!f);
907
+ const imagesUpdates = oldImages.filter((image) => oldFiles.has(image.id));
908
+ if (filesToUpload.length === 0) {
909
+ return imagesUpdates;
910
+ }
911
+ try {
912
+ const newsImages = await this.uploadStrapiFile(filesToUpload);
913
+ return [...imagesUpdates, ...newsImages];
914
+ } catch (error) {
915
+ console.error("Error al subir archivos:", error);
916
+ return [];
917
+ }
918
+ };
919
+ this.newUploadFile = async (resource, opt, serializeOptions) => {
920
+ const options = { ...serializeOptions };
921
+ const uri = opt?.url ?? "/strapi/upload-file";
922
+ const data = this.getRequestParams(opt);
923
+ options.exclude = ["id", ...options.exclude ?? []];
924
+ const formData = new FormData();
925
+ formData.append("files.files", resource);
926
+ data.body = formData;
927
+ const dataResponse = await this.postCall(uri, data);
928
+ return dataResponse;
929
+ };
930
+ this.config = {
931
+ onCreate: {
932
+ generateUID: config?.onCreate?.generateUID ?? true,
933
+ keyUID: config?.onCreate?.keyUID ?? "strapiUID"
934
+ },
935
+ defaultQueriesInvalidations: config?.defaultQueriesInvalidations ?? {},
936
+ prefix,
937
+ tokenKey,
938
+ wrapBodyInData: config?.wrapBodyInData ?? true,
939
+ transformResponse: config?.transformResponse ?? true,
940
+ pageSize: config?.pageSize ?? 15,
941
+ baseURL
942
+ };
943
+ }
944
+ getQueryParams(opt) {
945
+ const query = {
946
+ sort: opt?.sort || "id:asc",
947
+ pagination: {
948
+ page: opt?.pagination?.page || 1,
949
+ pageSize: opt?.pagination?.pageSize || this.config.pageSize
950
+ }
951
+ };
952
+ if (opt?.populate) query.populate = opt.populate;
953
+ query.filters = {
954
+ ...query.filters,
955
+ ...opt?.filters
956
+ };
957
+ if (opt?.fields) query.fields = opt.fields;
958
+ return query;
959
+ }
960
+ getRequestParams(opt) {
961
+ const options = {
962
+ auth: opt?.auth ?? true,
963
+ query: this.getQueryParams(opt)
964
+ };
965
+ return options;
966
+ }
967
+ async destroyFile(id) {
968
+ const uri = `${this.baseURL}/strapi/upload/files/${id}`;
969
+ await this.deleteCall(uri);
970
+ return true;
971
+ }
972
+ getInvalidateKeys(method, opt) {
973
+ const defaultKeys = this.defaultInvalidateKeys?.[method] ?? [[]];
974
+ const extraKeys = opt?.invalidateKeys ?? [];
975
+ return [...defaultKeys, ...extraKeys, [this.endpoint]];
976
+ }
977
+ };
978
+ export {
979
+ BaseAPI,
980
+ BaseUploaderAPI,
981
+ LocalStoreManager,
982
+ StrapiSDK,
983
+ StrapiUploaderSDK,
984
+ buildPath,
985
+ generateFakeFirebaseUID,
986
+ getKeyByValue,
987
+ helperStrapiAPI,
988
+ isDefined,
989
+ isEmptyObject,
990
+ isObject,
991
+ isPlainObject,
992
+ publicRoutes
993
+ };