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