@driveflux/api-swr 4.0.89 → 4.0.91

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,233 +1,3 @@
1
- function _array_like_to_array(arr, len) {
2
- if (len == null || len > arr.length) len = arr.length;
3
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
- return arr2;
5
- }
6
- function _array_with_holes(arr) {
7
- if (Array.isArray(arr)) return arr;
8
- }
9
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
- try {
11
- var info = gen[key](arg);
12
- var value = info.value;
13
- } catch (error) {
14
- reject(error);
15
- return;
16
- }
17
- if (info.done) {
18
- resolve(value);
19
- } else {
20
- Promise.resolve(value).then(_next, _throw);
21
- }
22
- }
23
- function _async_to_generator(fn) {
24
- return function() {
25
- var self = this, args = arguments;
26
- return new Promise(function(resolve, reject) {
27
- var gen = fn.apply(self, args);
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
- _next(undefined);
35
- });
36
- };
37
- }
38
- function _define_property(obj, key, value) {
39
- if (key in obj) {
40
- Object.defineProperty(obj, key, {
41
- value: value,
42
- enumerable: true,
43
- configurable: true,
44
- writable: true
45
- });
46
- } else {
47
- obj[key] = value;
48
- }
49
- return obj;
50
- }
51
- function _iterable_to_array_limit(arr, i) {
52
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
53
- if (_i == null) return;
54
- var _arr = [];
55
- var _n = true;
56
- var _d = false;
57
- var _s, _e;
58
- try {
59
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
60
- _arr.push(_s.value);
61
- if (i && _arr.length === i) break;
62
- }
63
- } catch (err) {
64
- _d = true;
65
- _e = err;
66
- } finally{
67
- try {
68
- if (!_n && _i["return"] != null) _i["return"]();
69
- } finally{
70
- if (_d) throw _e;
71
- }
72
- }
73
- return _arr;
74
- }
75
- function _non_iterable_rest() {
76
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
77
- }
78
- function _object_spread(target) {
79
- for(var i = 1; i < arguments.length; i++){
80
- var source = arguments[i] != null ? arguments[i] : {};
81
- var ownKeys = Object.keys(source);
82
- if (typeof Object.getOwnPropertySymbols === "function") {
83
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
84
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
85
- }));
86
- }
87
- ownKeys.forEach(function(key) {
88
- _define_property(target, key, source[key]);
89
- });
90
- }
91
- return target;
92
- }
93
- function ownKeys(object, enumerableOnly) {
94
- var keys = Object.keys(object);
95
- if (Object.getOwnPropertySymbols) {
96
- var symbols = Object.getOwnPropertySymbols(object);
97
- if (enumerableOnly) {
98
- symbols = symbols.filter(function(sym) {
99
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
100
- });
101
- }
102
- keys.push.apply(keys, symbols);
103
- }
104
- return keys;
105
- }
106
- function _object_spread_props(target, source) {
107
- source = source != null ? source : {};
108
- if (Object.getOwnPropertyDescriptors) {
109
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
110
- } else {
111
- ownKeys(Object(source)).forEach(function(key) {
112
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
113
- });
114
- }
115
- return target;
116
- }
117
- function _sliced_to_array(arr, i) {
118
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
119
- }
120
- function _type_of(obj) {
121
- "@swc/helpers - typeof";
122
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
123
- }
124
- function _unsupported_iterable_to_array(o, minLen) {
125
- if (!o) return;
126
- if (typeof o === "string") return _array_like_to_array(o, minLen);
127
- var n = Object.prototype.toString.call(o).slice(8, -1);
128
- if (n === "Object" && o.constructor) n = o.constructor.name;
129
- if (n === "Map" || n === "Set") return Array.from(n);
130
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
131
- }
132
- function _ts_generator(thisArg, body) {
133
- var f, y, t, _ = {
134
- label: 0,
135
- sent: function() {
136
- if (t[0] & 1) throw t[1];
137
- return t[1];
138
- },
139
- trys: [],
140
- ops: []
141
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
142
- return d(g, "next", {
143
- value: verb(0)
144
- }), d(g, "throw", {
145
- value: verb(1)
146
- }), d(g, "return", {
147
- value: verb(2)
148
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
149
- value: function() {
150
- return this;
151
- }
152
- }), g;
153
- function verb(n) {
154
- return function(v) {
155
- return step([
156
- n,
157
- v
158
- ]);
159
- };
160
- }
161
- function step(op) {
162
- if (f) throw new TypeError("Generator is already executing.");
163
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
164
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
165
- if (y = 0, t) op = [
166
- op[0] & 2,
167
- t.value
168
- ];
169
- switch(op[0]){
170
- case 0:
171
- case 1:
172
- t = op;
173
- break;
174
- case 4:
175
- _.label++;
176
- return {
177
- value: op[1],
178
- done: false
179
- };
180
- case 5:
181
- _.label++;
182
- y = op[1];
183
- op = [
184
- 0
185
- ];
186
- continue;
187
- case 7:
188
- op = _.ops.pop();
189
- _.trys.pop();
190
- continue;
191
- default:
192
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
193
- _ = 0;
194
- continue;
195
- }
196
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
197
- _.label = op[1];
198
- break;
199
- }
200
- if (op[0] === 6 && _.label < t[1]) {
201
- _.label = t[1];
202
- t = op;
203
- break;
204
- }
205
- if (t && _.label < t[2]) {
206
- _.label = t[2];
207
- _.ops.push(op);
208
- break;
209
- }
210
- if (t[2]) _.ops.pop();
211
- _.trys.pop();
212
- continue;
213
- }
214
- op = body.call(thisArg, _);
215
- } catch (e) {
216
- op = [
217
- 6,
218
- e
219
- ];
220
- y = 0;
221
- } finally{
222
- f = t = 0;
223
- }
224
- if (op[0] & 5) throw op[1];
225
- return {
226
- value: op[0] ? op[1] : void 0,
227
- done: true
228
- };
229
- }
230
- }
231
1
  import { useAuth } from '@driveflux/auth/react/providers';
232
2
  import { config } from '@driveflux/config/frontend';
233
3
  import { enhancedFetch } from '@driveflux/fetch';
@@ -239,182 +9,124 @@ import useSWRInfinite from 'swr/infinite';
239
9
  *
240
10
  * @important instead of returning a result, this will always return Success or throw an error containing Error
241
11
  * @important if the 3rd param provides an Authorization header, it will be ignored!
242
- */ export var fetchWithAuth = function fetchWithAuth(urlParams) {
243
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
244
- return _async_to_generator(function() {
245
- var _result_metadata, _ref, url, accessToken, otherOptions, apiHost, finalUrl, correlationIdFromSessionStorage, result, correlationId, _result_metadata1;
246
- return _ts_generator(this, function(_state) {
247
- switch(_state.label){
248
- case 0:
249
- _ref = _sliced_to_array(Array.isArray(urlParams) ? urlParams : [
250
- urlParams,
251
- null
252
- ], 3), url = _ref[0], accessToken = _ref[1], otherOptions = _ref[2];
253
- apiHost = config.appUrl;
254
- finalUrl = url.startsWith('/') ? "".concat(apiHost).concat(url) : url;
255
- correlationIdFromSessionStorage = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('x-correlation-id') : null;
256
- return [
257
- 4,
258
- enhancedFetch(finalUrl, _object_spread_props(_object_spread({}, options, otherOptions), {
259
- headers: _object_spread({}, options.headers || {}, (otherOptions === null || otherOptions === void 0 ? void 0 : otherOptions.headers) || {}, accessToken ? {
260
- Authorization: "Bearer ".concat(accessToken)
261
- } : {}, correlationIdFromSessionStorage ? {
262
- 'x-correlation-id': correlationIdFromSessionStorage
263
- } : {})
264
- }))
265
- ];
266
- case 1:
267
- result = _state.sent();
268
- correlationId = (_result_metadata = result.metadata) === null || _result_metadata === void 0 ? void 0 : _result_metadata.headers.get('x-correlation-id');
269
- if (correlationId && typeof sessionStorage !== 'undefined') {
270
- ;
271
- // We store the correlation id in the session storage so that we can use it in the next request
272
- sessionStorage.setItem('x-correlation-id', ((_result_metadata1 = result.metadata) === null || _result_metadata1 === void 0 ? void 0 : _result_metadata1.headers.get('x-correlation-id')) || '');
273
- }
274
- if (!result.ok) {
275
- throw result.val;
276
- }
277
- return [
278
- 2,
279
- result.val
280
- ];
281
- }
282
- });
283
- })();
284
- };
285
- export var isStructuredResponse = function isStructuredResponse(obj) {
286
- return obj && (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === 'object' && obj.metadata;
12
+ */
13
+ export const fetchWithAuth = async (urlParams, options = {}) => {
14
+ const [url, accessToken, otherOptions] = Array.isArray(urlParams)
15
+ ? urlParams
16
+ : [urlParams, null];
17
+ const apiHost = config.appUrl;
18
+ const finalUrl = url.startsWith('/') ? `${apiHost}${url}` : url;
19
+ const correlationIdFromSessionStorage = typeof sessionStorage !== 'undefined'
20
+ ? sessionStorage.getItem('x-correlation-id')
21
+ : null;
22
+ const result = await enhancedFetch(finalUrl, {
23
+ ...options,
24
+ ...otherOptions,
25
+ headers: {
26
+ ...(options.headers || {}),
27
+ ...(otherOptions?.headers || {}),
28
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
29
+ ...(correlationIdFromSessionStorage
30
+ ? { 'x-correlation-id': correlationIdFromSessionStorage }
31
+ : {}),
32
+ },
33
+ });
34
+ const correlationId = result.metadata?.headers.get('x-correlation-id');
35
+ if (correlationId && typeof sessionStorage !== 'undefined') {
36
+ // We store the correlation id in the session storage so that we can use it in the next request
37
+ sessionStorage.setItem('x-correlation-id', result.metadata?.headers.get('x-correlation-id') || '');
38
+ }
39
+ if (!result.ok) {
40
+ throw result.val;
41
+ }
42
+ return result.val;
287
43
  };
288
- export var swrFetch = function swrFetch(url) {
289
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
290
- return _async_to_generator(function() {
291
- var _response_metadata, correlationIdFromSessionStorage, response, correlationId, _response_metadata1;
292
- return _ts_generator(this, function(_state) {
293
- switch(_state.label){
294
- case 0:
295
- correlationIdFromSessionStorage = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('x-correlation-id') : null;
296
- return [
297
- 4,
298
- enhancedFetch(url, _object_spread_props(_object_spread({}, options), {
299
- headers: _object_spread({}, options.headers || {}, correlationIdFromSessionStorage ? {
300
- 'x-correlation-id': correlationIdFromSessionStorage
301
- } : {})
302
- }))
303
- ];
304
- case 1:
305
- response = _state.sent();
306
- correlationId = (_response_metadata = response.metadata) === null || _response_metadata === void 0 ? void 0 : _response_metadata.headers.get('x-correlation-id');
307
- if (correlationId && typeof sessionStorage !== 'undefined') {
308
- ;
309
- // We store the correlation id in the session storage so that we can use it in the next request
310
- sessionStorage.setItem('x-correlation-id', ((_response_metadata1 = response.metadata) === null || _response_metadata1 === void 0 ? void 0 : _response_metadata1.headers.get('x-correlation-id')) || '');
311
- }
312
- if (response.ok) {
313
- return [
314
- 2,
315
- response.val
316
- ];
317
- }
318
- throw response.val;
319
- }
320
- });
321
- })();
44
+ export const isStructuredResponse = (obj) => {
45
+ return obj && typeof obj === 'object' && obj.metadata;
322
46
  };
323
- export var useApi = function useApi(key, config) {
324
- var result = useSWR(key, function(url) {
325
- return swrFetch(url);
326
- }, config);
327
- return _object_spread_props(_object_spread({}, result), {
328
- revalidate: function revalidate() {
329
- return _async_to_generator(function() {
330
- return _ts_generator(this, function(_state) {
331
- switch(_state.label){
332
- case 0:
333
- return [
334
- 4,
335
- result.mutate()
336
- ];
337
- case 1:
338
- return [
339
- 2,
340
- !!_state.sent()
341
- ];
342
- }
343
- });
344
- })();
345
- }
47
+ export const swrFetch = async (url, options = {}) => {
48
+ const correlationIdFromSessionStorage = typeof sessionStorage !== 'undefined'
49
+ ? sessionStorage.getItem('x-correlation-id')
50
+ : null;
51
+ const response = await enhancedFetch(url, {
52
+ ...options,
53
+ headers: {
54
+ ...(options.headers || {}),
55
+ ...(correlationIdFromSessionStorage
56
+ ? { 'x-correlation-id': correlationIdFromSessionStorage }
57
+ : {}),
58
+ },
346
59
  });
60
+ const correlationId = response.metadata?.headers.get('x-correlation-id');
61
+ if (correlationId && typeof sessionStorage !== 'undefined') {
62
+ // We store the correlation id in the session storage so that we can use it in the next request
63
+ sessionStorage.setItem('x-correlation-id', response.metadata?.headers.get('x-correlation-id') || '');
64
+ }
65
+ if (response.ok) {
66
+ return response.val;
67
+ }
68
+ throw response.val;
347
69
  };
348
- export var useApiWithAuth = function useApiWithAuth(key, config) {
70
+ export const useApi = (key, config) => {
71
+ const result = useSWR(key, (url) => swrFetch(url), config);
72
+ return {
73
+ ...result,
74
+ revalidate: async () => !!(await result.mutate()),
75
+ };
76
+ };
77
+ export const useApiWithAuth = (key, config) => {
349
78
  // TODO
350
- var accessToken = useAuth().accessToken;
351
- var result = useSWR(key ? Array.isArray(key) ? key : [
352
- key,
353
- accessToken
354
- ] : null, fetchWithAuth, config);
355
- return _object_spread_props(_object_spread({}, result), {
356
- revalidate: result.mutate
357
- });
79
+ const { accessToken } = useAuth();
80
+ const result = useSWR(key ? (Array.isArray(key) ? key : [key, accessToken]) : null, fetchWithAuth, config);
81
+ return {
82
+ ...result,
83
+ revalidate: result.mutate,
84
+ };
358
85
  };
359
- export var usePaginationApiWithAuth = function usePaginationApiWithAuth(key, config) {
86
+ export const usePaginationApiWithAuth = (key, config) => {
360
87
  // TODO
361
- var accessToken = useAuth().accessToken;
362
- var result = useSWRInfinite(function(i, p) {
363
- var res = null;
88
+ const { accessToken } = useAuth();
89
+ const result = useSWRInfinite((i, p) => {
90
+ let res = null;
364
91
  if (typeof key === 'function') {
365
92
  res = key(i, p);
366
- } else if (isStructuredResponse(p) && key) {
367
- var _p_metadata, _p_metadata1;
368
- if (((_p_metadata = p.metadata) === null || _p_metadata === void 0 ? void 0 : _p_metadata.nextSkip) === null) {
369
- return null // reached the end
370
- ;
93
+ }
94
+ else if (isStructuredResponse(p) && key) {
95
+ if (p.metadata?.nextSkip === null) {
96
+ return null; // reached the end
371
97
  }
372
- var separator = key.indexOf('?') !== -1 ? '&' : '?';
373
- res = ((_p_metadata1 = p.metadata) === null || _p_metadata1 === void 0 ? void 0 : _p_metadata1.nextSkip) ? "".concat(key).concat(separator, "skip=").concat(p.metadata.nextSkip) : key;
374
- } else if (!p) {
98
+ const separator = key.indexOf('?') !== -1 ? '&' : '?';
99
+ res = p.metadata?.nextSkip
100
+ ? `${key}${separator}skip=${p.metadata.nextSkip}`
101
+ : key;
102
+ }
103
+ else if (!p) {
375
104
  res = key;
376
- } else {
105
+ }
106
+ else {
377
107
  console.error('Wrong key loader or data type supplied to pagination');
378
108
  return null;
379
109
  }
380
- return [
381
- res,
382
- accessToken
383
- ];
110
+ return [res, accessToken];
384
111
  }, fetchWithAuth, config);
385
- return _object_spread_props(_object_spread({}, result), {
386
- revalidate: function revalidate() {
387
- return _async_to_generator(function() {
388
- return _ts_generator(this, function(_state) {
389
- switch(_state.label){
390
- case 0:
391
- return [
392
- 4,
393
- result.mutate()
394
- ];
395
- case 1:
396
- return [
397
- 2,
398
- !!_state.sent()
399
- ];
400
- }
401
- });
402
- })();
403
- }
404
- });
112
+ return {
113
+ ...result,
114
+ revalidate: async () => !!(await result.mutate()),
115
+ };
405
116
  };
406
117
  /**
407
118
  * TODO
408
119
  * @deprecated
409
- */ export var useAuthenticatedFetch = function useAuthenticatedFetch(url) {
410
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
411
- var accessToken = useAuth().accessToken;
412
- var headers = _object_spread({}, accessToken ? {
413
- Authorization: "Bearer ".concat(accessToken)
414
- } : undefined, (options === null || options === void 0 ? void 0 : options.headers) || {});
415
- return function() {
416
- return enhancedFetch(url, _object_spread({
417
- headers: headers
418
- }, options));
120
+ */
121
+ export const useAuthenticatedFetch = (url, options = {}) => {
122
+ const { accessToken } = useAuth();
123
+ const headers = {
124
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
125
+ ...(options?.headers || {}),
419
126
  };
127
+ return () => enhancedFetch(url, {
128
+ headers,
129
+ ...options,
130
+ });
420
131
  };
132
+ //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
1
  import { config } from '@driveflux/config/frontend';
2
- export var API_MODELS_URLS = {
2
+ export const API_MODELS_URLS = {
3
3
  Business: '/api/businesses',
4
4
  User: '/api/users',
5
5
  Inquiry: '/api/inquiries',
@@ -11,11 +11,14 @@ export var API_MODELS_URLS = {
11
11
  Invoice: '/api/invoices',
12
12
  SubscriptionReservation: '/api/reservations',
13
13
  SubscriptionContract: '/api/subscription-contracts',
14
- EmailSent: '/api/emails-sent'
14
+ EmailSent: '/api/emails-sent',
15
15
  };
16
16
  export function getApiUrl(model) {
17
- if (model.startsWith('/api') || model.startsWith("".concat(config.apiUrl))) {
17
+ if (model.startsWith('/api') || model.startsWith(`${config.apiUrl}`)) {
18
18
  return model;
19
19
  }
20
- return model in API_MODELS_URLS ? API_MODELS_URLS[model] : "/api/".concat(model);
20
+ return model in API_MODELS_URLS
21
+ ? API_MODELS_URLS[model]
22
+ : `/api/${model}`;
21
23
  }
24
+ //# sourceMappingURL=api-models.js.map
package/dist/fetcher.js CHANGED
@@ -1,229 +1,3 @@
1
- function _array_like_to_array(arr, len) {
2
- if (len == null || len > arr.length) len = arr.length;
3
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
- return arr2;
5
- }
6
- function _array_with_holes(arr) {
7
- if (Array.isArray(arr)) return arr;
8
- }
9
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
- try {
11
- var info = gen[key](arg);
12
- var value = info.value;
13
- } catch (error) {
14
- reject(error);
15
- return;
16
- }
17
- if (info.done) {
18
- resolve(value);
19
- } else {
20
- Promise.resolve(value).then(_next, _throw);
21
- }
22
- }
23
- function _async_to_generator(fn) {
24
- return function() {
25
- var self = this, args = arguments;
26
- return new Promise(function(resolve, reject) {
27
- var gen = fn.apply(self, args);
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
- _next(undefined);
35
- });
36
- };
37
- }
38
- function _define_property(obj, key, value) {
39
- if (key in obj) {
40
- Object.defineProperty(obj, key, {
41
- value: value,
42
- enumerable: true,
43
- configurable: true,
44
- writable: true
45
- });
46
- } else {
47
- obj[key] = value;
48
- }
49
- return obj;
50
- }
51
- function _iterable_to_array_limit(arr, i) {
52
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
53
- if (_i == null) return;
54
- var _arr = [];
55
- var _n = true;
56
- var _d = false;
57
- var _s, _e;
58
- try {
59
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
60
- _arr.push(_s.value);
61
- if (i && _arr.length === i) break;
62
- }
63
- } catch (err) {
64
- _d = true;
65
- _e = err;
66
- } finally{
67
- try {
68
- if (!_n && _i["return"] != null) _i["return"]();
69
- } finally{
70
- if (_d) throw _e;
71
- }
72
- }
73
- return _arr;
74
- }
75
- function _non_iterable_rest() {
76
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
77
- }
78
- function _object_spread(target) {
79
- for(var i = 1; i < arguments.length; i++){
80
- var source = arguments[i] != null ? arguments[i] : {};
81
- var ownKeys = Object.keys(source);
82
- if (typeof Object.getOwnPropertySymbols === "function") {
83
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
84
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
85
- }));
86
- }
87
- ownKeys.forEach(function(key) {
88
- _define_property(target, key, source[key]);
89
- });
90
- }
91
- return target;
92
- }
93
- function ownKeys(object, enumerableOnly) {
94
- var keys = Object.keys(object);
95
- if (Object.getOwnPropertySymbols) {
96
- var symbols = Object.getOwnPropertySymbols(object);
97
- if (enumerableOnly) {
98
- symbols = symbols.filter(function(sym) {
99
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
100
- });
101
- }
102
- keys.push.apply(keys, symbols);
103
- }
104
- return keys;
105
- }
106
- function _object_spread_props(target, source) {
107
- source = source != null ? source : {};
108
- if (Object.getOwnPropertyDescriptors) {
109
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
110
- } else {
111
- ownKeys(Object(source)).forEach(function(key) {
112
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
113
- });
114
- }
115
- return target;
116
- }
117
- function _sliced_to_array(arr, i) {
118
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
119
- }
120
- function _unsupported_iterable_to_array(o, minLen) {
121
- if (!o) return;
122
- if (typeof o === "string") return _array_like_to_array(o, minLen);
123
- var n = Object.prototype.toString.call(o).slice(8, -1);
124
- if (n === "Object" && o.constructor) n = o.constructor.name;
125
- if (n === "Map" || n === "Set") return Array.from(n);
126
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
127
- }
128
- function _ts_generator(thisArg, body) {
129
- var f, y, t, _ = {
130
- label: 0,
131
- sent: function() {
132
- if (t[0] & 1) throw t[1];
133
- return t[1];
134
- },
135
- trys: [],
136
- ops: []
137
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
138
- return d(g, "next", {
139
- value: verb(0)
140
- }), d(g, "throw", {
141
- value: verb(1)
142
- }), d(g, "return", {
143
- value: verb(2)
144
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
145
- value: function() {
146
- return this;
147
- }
148
- }), g;
149
- function verb(n) {
150
- return function(v) {
151
- return step([
152
- n,
153
- v
154
- ]);
155
- };
156
- }
157
- function step(op) {
158
- if (f) throw new TypeError("Generator is already executing.");
159
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
160
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
161
- if (y = 0, t) op = [
162
- op[0] & 2,
163
- t.value
164
- ];
165
- switch(op[0]){
166
- case 0:
167
- case 1:
168
- t = op;
169
- break;
170
- case 4:
171
- _.label++;
172
- return {
173
- value: op[1],
174
- done: false
175
- };
176
- case 5:
177
- _.label++;
178
- y = op[1];
179
- op = [
180
- 0
181
- ];
182
- continue;
183
- case 7:
184
- op = _.ops.pop();
185
- _.trys.pop();
186
- continue;
187
- default:
188
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
189
- _ = 0;
190
- continue;
191
- }
192
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
193
- _.label = op[1];
194
- break;
195
- }
196
- if (op[0] === 6 && _.label < t[1]) {
197
- _.label = t[1];
198
- t = op;
199
- break;
200
- }
201
- if (t && _.label < t[2]) {
202
- _.label = t[2];
203
- _.ops.push(op);
204
- break;
205
- }
206
- if (t[2]) _.ops.pop();
207
- _.trys.pop();
208
- continue;
209
- }
210
- op = body.call(thisArg, _);
211
- } catch (e) {
212
- op = [
213
- 6,
214
- e
215
- ];
216
- y = 0;
217
- } finally{
218
- f = t = 0;
219
- }
220
- if (op[0] & 5) throw op[1];
221
- return {
222
- value: op[0] ? op[1] : void 0,
223
- done: true
224
- };
225
- }
226
- }
227
1
  import { config } from '@driveflux/config/frontend';
228
2
  import { enhancedFetch } from '@driveflux/fetch';
229
3
  /**
@@ -232,46 +6,34 @@ import { enhancedFetch } from '@driveflux/fetch';
232
6
  *
233
7
  * @important instead of returning a result, this will always return Success or throw an error containing Error
234
8
  * @important if the 3rd param provides an Authorization header, it will be ignored!
235
- */ export var fetchWithAuth = function fetchWithAuth(urlParams) {
236
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
237
- return _async_to_generator(function() {
238
- var _result_metadata, _ref, url, accessToken, apiHost, finalUrl, correlationIdFromSessionStorage, result, correlationId, _result_metadata1;
239
- return _ts_generator(this, function(_state) {
240
- switch(_state.label){
241
- case 0:
242
- _ref = _sliced_to_array(Array.isArray(urlParams) ? urlParams : [
243
- urlParams,
244
- null
245
- ], 2), url = _ref[0], accessToken = _ref[1];
246
- apiHost = config.appUrl;
247
- finalUrl = url.startsWith('/') ? "".concat(apiHost).concat(url) : url;
248
- correlationIdFromSessionStorage = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('x-correlation-id') : null;
249
- return [
250
- 4,
251
- enhancedFetch(finalUrl, _object_spread_props(_object_spread({}, options), {
252
- headers: _object_spread({}, options.headers || {}, accessToken ? {
253
- Authorization: "Bearer ".concat(accessToken)
254
- } : {}, correlationIdFromSessionStorage ? {
255
- 'x-correlation-id': correlationIdFromSessionStorage
256
- } : {})
257
- }))
258
- ];
259
- case 1:
260
- result = _state.sent();
261
- correlationId = (_result_metadata = result.metadata) === null || _result_metadata === void 0 ? void 0 : _result_metadata.headers.get('x-correlation-id');
262
- if (correlationId && typeof sessionStorage !== 'undefined') {
263
- ;
264
- // We store the correlation id in the session storage so that we can use it in the next request
265
- sessionStorage.setItem('x-correlation-id', ((_result_metadata1 = result.metadata) === null || _result_metadata1 === void 0 ? void 0 : _result_metadata1.headers.get('x-correlation-id')) || '');
266
- }
267
- if (!result.ok) {
268
- throw result.val;
269
- }
270
- return [
271
- 2,
272
- result.val
273
- ];
274
- }
275
- });
276
- })();
9
+ */
10
+ export const fetchWithAuth = async (urlParams, options = {}) => {
11
+ const [url, accessToken] = Array.isArray(urlParams)
12
+ ? urlParams
13
+ : [urlParams, null];
14
+ const apiHost = config.appUrl;
15
+ const finalUrl = url.startsWith('/') ? `${apiHost}${url}` : url;
16
+ const correlationIdFromSessionStorage = typeof sessionStorage !== 'undefined'
17
+ ? sessionStorage.getItem('x-correlation-id')
18
+ : null;
19
+ const result = await enhancedFetch(finalUrl, {
20
+ ...options,
21
+ headers: {
22
+ ...(options.headers || {}),
23
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
24
+ ...(correlationIdFromSessionStorage
25
+ ? { 'x-correlation-id': correlationIdFromSessionStorage }
26
+ : {}),
27
+ },
28
+ });
29
+ const correlationId = result.metadata?.headers.get('x-correlation-id');
30
+ if (correlationId && typeof sessionStorage !== 'undefined') {
31
+ // We store the correlation id in the session storage so that we can use it in the next request
32
+ sessionStorage.setItem('x-correlation-id', result.metadata?.headers.get('x-correlation-id') || '');
33
+ }
34
+ if (!result.ok) {
35
+ throw result.val;
36
+ }
37
+ return result.val;
277
38
  };
39
+ //# sourceMappingURL=fetcher.js.map
package/dist/index.js CHANGED
@@ -1,91 +1,3 @@
1
- function _define_property(obj, key, value) {
2
- if (key in obj) {
3
- Object.defineProperty(obj, key, {
4
- value: value,
5
- enumerable: true,
6
- configurable: true,
7
- writable: true
8
- });
9
- } else {
10
- obj[key] = value;
11
- }
12
- return obj;
13
- }
14
- function _object_spread(target) {
15
- for(var i = 1; i < arguments.length; i++){
16
- var source = arguments[i] != null ? arguments[i] : {};
17
- var ownKeys = Object.keys(source);
18
- if (typeof Object.getOwnPropertySymbols === "function") {
19
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
20
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
21
- }));
22
- }
23
- ownKeys.forEach(function(key) {
24
- _define_property(target, key, source[key]);
25
- });
26
- }
27
- return target;
28
- }
29
- function ownKeys(object, enumerableOnly) {
30
- var keys = Object.keys(object);
31
- if (Object.getOwnPropertySymbols) {
32
- var symbols = Object.getOwnPropertySymbols(object);
33
- if (enumerableOnly) {
34
- symbols = symbols.filter(function(sym) {
35
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
36
- });
37
- }
38
- keys.push.apply(keys, symbols);
39
- }
40
- return keys;
41
- }
42
- function _object_spread_props(target, source) {
43
- source = source != null ? source : {};
44
- if (Object.getOwnPropertyDescriptors) {
45
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
46
- } else {
47
- ownKeys(Object(source)).forEach(function(key) {
48
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
49
- });
50
- }
51
- return target;
52
- }
53
- function _object_without_properties(source, excluded) {
54
- if (source == null) return {};
55
- var target = {}, sourceKeys, key, i;
56
- if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
57
- sourceKeys = Reflect.ownKeys(Object(source));
58
- for(i = 0; i < sourceKeys.length; i++){
59
- key = sourceKeys[i];
60
- if (excluded.indexOf(key) >= 0) continue;
61
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
62
- target[key] = source[key];
63
- }
64
- return target;
65
- }
66
- target = _object_without_properties_loose(source, excluded);
67
- if (Object.getOwnPropertySymbols) {
68
- sourceKeys = Object.getOwnPropertySymbols(source);
69
- for(i = 0; i < sourceKeys.length; i++){
70
- key = sourceKeys[i];
71
- if (excluded.indexOf(key) >= 0) continue;
72
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
73
- target[key] = source[key];
74
- }
75
- }
76
- return target;
77
- }
78
- function _object_without_properties_loose(source, excluded) {
79
- if (source == null) return {};
80
- var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
81
- for(i = 0; i < sourceKeys.length; i++){
82
- key = sourceKeys[i];
83
- if (excluded.indexOf(key) >= 0) continue;
84
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
85
- target[key] = source[key];
86
- }
87
- return target;
88
- }
89
1
  import { useAuth } from '@driveflux/auth/react/providers';
90
2
  import isEmpty from 'lodash/isEmpty.js';
91
3
  import { useCallback } from 'react';
@@ -94,62 +6,55 @@ import useSWRInfinite from 'swr/infinite';
94
6
  import { getApiUrl } from './api-models.js';
95
7
  import { fetchWithAuth } from './fetcher.js';
96
8
  import { makeQueryParams } from './utils.js';
97
- var getKeyMaker = function getKeyMaker(model, pageSize, query, accessToken) {
98
- var resource = getApiUrl(model);
99
- var loader = function loader(pageIndex, previousPageData) {
9
+ const getKeyMaker = (model, pageSize, query, accessToken) => {
10
+ const resource = getApiUrl(model);
11
+ const loader = (pageIndex, previousPageData) => {
100
12
  if (previousPageData && !previousPageData.next) {
101
13
  return null;
102
14
  }
103
- var makeFinalQuery = function makeFinalQuery(index) {
104
- var take = (previousPageData === null || previousPageData === void 0 ? void 0 : previousPageData.take) || pageSize;
105
- return _object_spread_props(_object_spread({}, query), {
106
- skip: (previousPageData === null || previousPageData === void 0 ? void 0 : previousPageData.skip) || (take ? index * take : undefined),
107
- take: take
108
- });
15
+ const makeFinalQuery = (index) => {
16
+ const take = previousPageData?.take || pageSize;
17
+ return {
18
+ ...query,
19
+ skip: previousPageData?.skip || (take ? index * take : undefined),
20
+ take,
21
+ };
109
22
  };
110
- var finalQuery = makeFinalQuery(pageIndex);
111
- var queryString = !isEmpty(finalQuery) ? "?".concat(makeQueryParams(finalQuery)) : '';
112
- var url = "".concat(resource).concat(queryString);
113
- var nextQuery = makeFinalQuery(pageIndex + 1);
114
- var nextQueryString = !isEmpty(nextQuery) ? "?".concat(makeQueryParams(nextQuery)) : '';
115
- var nextUrl = "".concat(resource).concat(nextQueryString);
23
+ const finalQuery = makeFinalQuery(pageIndex);
24
+ const queryString = !isEmpty(finalQuery)
25
+ ? `?${makeQueryParams(finalQuery)}`
26
+ : '';
27
+ const url = `${resource}${queryString}`;
28
+ const nextQuery = makeFinalQuery(pageIndex + 1);
29
+ const nextQueryString = !isEmpty(nextQuery)
30
+ ? `?${makeQueryParams(nextQuery)}`
31
+ : '';
32
+ const nextUrl = `${resource}${nextQueryString}`;
116
33
  // Preload next page
117
- preload([
118
- nextUrl,
119
- accessToken
120
- ], fetchWithAuth);
121
- return [
122
- url,
123
- accessToken
124
- ];
34
+ preload([nextUrl, accessToken], fetchWithAuth);
35
+ return [url, accessToken];
125
36
  };
126
37
  return loader;
127
38
  };
128
- export var useApiPagination = function useApiPagination(model, _1) {
129
- var pageSize = _1.pageSize, query = _1.query, swrConfig = _object_without_properties(_1, [
130
- "pageSize",
131
- "query"
132
- ]);
133
- var _result_data_, _result_data;
39
+ export const useApiPagination = (model, { pageSize, query, ...swrConfig }) => {
134
40
  // TODO
135
- var accessToken = useAuth().accessToken;
136
- var result = useSWRInfinite(getKeyMaker(model, pageSize || 20, query, accessToken), fetchWithAuth, _object_spread({
137
- parallel: true
138
- }, swrConfig));
139
- var hasMore = ((result === null || result === void 0 ? void 0 : (_result_data = result.data) === null || _result_data === void 0 ? void 0 : (_result_data_ = _result_data[0]) === null || _result_data_ === void 0 ? void 0 : _result_data_.count) || 0) > result.size * (pageSize || 20);
140
- var next = useCallback(function() {
41
+ const { accessToken } = useAuth();
42
+ const result = useSWRInfinite(getKeyMaker(model, pageSize || 20, query, accessToken), fetchWithAuth, {
43
+ parallel: true,
44
+ ...swrConfig,
45
+ });
46
+ const hasMore = (result?.data?.[0]?.count || 0) > result.size * (pageSize || 20);
47
+ const next = useCallback(() => {
141
48
  if (!hasMore) {
142
49
  return;
143
50
  }
144
51
  result.setSize(result.size + 1);
145
- }, [
52
+ }, [hasMore, result?.size, result.setSize]);
53
+ return {
54
+ ...result,
55
+ next,
146
56
  hasMore,
147
- result === null || result === void 0 ? void 0 : result.size,
148
- result.setSize
149
- ]);
150
- return _object_spread_props(_object_spread({}, result), {
151
- next: next,
152
- hasMore: hasMore
153
- });
57
+ };
154
58
  };
155
59
  export * from './utils.js';
60
+ //# sourceMappingURL=index.js.map
package/dist/utils.js CHANGED
@@ -1,109 +1,24 @@
1
- function _array_like_to_array(arr, len) {
2
- if (len == null || len > arr.length) len = arr.length;
3
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
- return arr2;
5
- }
6
- function _array_with_holes(arr) {
7
- if (Array.isArray(arr)) return arr;
8
- }
9
- function _instanceof(left, right) {
10
- "@swc/helpers - instanceof";
11
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
12
- return !!right[Symbol.hasInstance](left);
13
- } else {
14
- return left instanceof right;
15
- }
16
- }
17
- function _iterable_to_array_limit(arr, i) {
18
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
19
- if (_i == null) return;
20
- var _arr = [];
21
- var _n = true;
22
- var _d = false;
23
- var _s, _e;
24
- try {
25
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
26
- _arr.push(_s.value);
27
- if (i && _arr.length === i) break;
28
- }
29
- } catch (err) {
30
- _d = true;
31
- _e = err;
32
- } finally{
33
- try {
34
- if (!_n && _i["return"] != null) _i["return"]();
35
- } finally{
36
- if (_d) throw _e;
37
- }
38
- }
39
- return _arr;
40
- }
41
- function _non_iterable_rest() {
42
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
43
- }
44
- function _sliced_to_array(arr, i) {
45
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
46
- }
47
- function _unsupported_iterable_to_array(o, minLen) {
48
- if (!o) return;
49
- if (typeof o === "string") return _array_like_to_array(o, minLen);
50
- var n = Object.prototype.toString.call(o).slice(8, -1);
51
- if (n === "Object" && o.constructor) n = o.constructor.name;
52
- if (n === "Map" || n === "Set") return Array.from(n);
53
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
54
- }
55
- export var makeQueryParams = function makeQueryParams(params) {
56
- if (_instanceof(params, URLSearchParams)) {
1
+ export const makeQueryParams = (params) => {
2
+ if (params instanceof URLSearchParams) {
57
3
  return params.toString();
58
4
  }
59
- var newParams = new URLSearchParams();
60
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
61
- try {
62
- for(var _iterator = Object.entries(params)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
63
- var _step_value = _sliced_to_array(_step.value, 2), key = _step_value[0], value = _step_value[1];
64
- appendParam(newParams, key, value);
65
- }
66
- } catch (err) {
67
- _didIteratorError = true;
68
- _iteratorError = err;
69
- } finally{
70
- try {
71
- if (!_iteratorNormalCompletion && _iterator.return != null) {
72
- _iterator.return();
73
- }
74
- } finally{
75
- if (_didIteratorError) {
76
- throw _iteratorError;
77
- }
78
- }
5
+ const newParams = new URLSearchParams();
6
+ for (const [key, value] of Object.entries(params)) {
7
+ appendParam(newParams, key, value);
79
8
  }
80
9
  return newParams.toString();
81
10
  };
82
- var appendParam = function appendParam1(params, key, value) {
11
+ const appendParam = (params, key, value) => {
83
12
  if (Array.isArray(value)) {
84
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
85
- try {
86
- for(var _iterator = value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
87
- var v = _step.value;
88
- appendParam(params, key, v);
89
- }
90
- } catch (err) {
91
- _didIteratorError = true;
92
- _iteratorError = err;
93
- } finally{
94
- try {
95
- if (!_iteratorNormalCompletion && _iterator.return != null) {
96
- _iterator.return();
97
- }
98
- } finally{
99
- if (_didIteratorError) {
100
- throw _iteratorError;
101
- }
102
- }
13
+ for (const v of value) {
14
+ appendParam(params, key, v);
103
15
  }
104
- } else if (_instanceof(value, Date)) {
16
+ }
17
+ else if (value instanceof Date) {
105
18
  params.append(key, value.toISOString());
106
- } else if (value !== undefined && value !== null) {
19
+ }
20
+ else if (value !== undefined && value !== null) {
107
21
  params.append(key, value.toString());
108
22
  }
109
23
  };
24
+ //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@driveflux/api-swr",
3
- "version": "4.0.89",
3
+ "version": "4.0.91",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -16,23 +16,23 @@
16
16
  "dist"
17
17
  ],
18
18
  "dependencies": {
19
- "@driveflux/auth": "4.0.88",
20
- "@driveflux/config": "3.0.11",
21
- "@driveflux/db": "4.1.19",
22
- "@driveflux/fetch": "8.0.2",
23
- "@driveflux/problem": "6.0.2",
24
- "@driveflux/result": "6.0.2",
19
+ "@driveflux/auth": "4.0.90",
20
+ "@driveflux/config": "3.0.12",
21
+ "@driveflux/db": "4.1.20",
22
+ "@driveflux/fetch": "8.0.3",
23
+ "@driveflux/problem": "6.0.3",
24
+ "@driveflux/result": "6.0.3",
25
25
  "lodash": "^4.18.1",
26
26
  "swr": "^2.4.1"
27
27
  },
28
28
  "devDependencies": {
29
- "@driveflux/fab": "4.0.1",
30
- "@driveflux/tsconfig": "3.0.1",
29
+ "@driveflux/fab": "4.0.2",
30
+ "@driveflux/tsconfig": "3.0.2",
31
31
  "@swc/cli": "^0.8.1",
32
32
  "@swc/core": "^1.15.33",
33
33
  "@types/lodash": "^4.17.24",
34
- "@types/node": "^25.7.0",
35
- "@types/react": "19.2.14",
34
+ "@types/node": "^25.9.1",
35
+ "@types/react": "19.2.15",
36
36
  "del-cli": "^7.0.0",
37
37
  "react": "19.2.6",
38
38
  "typescript": "^6.0.3"