@react-pakistan/util-functions 1.25.19 → 1.25.21

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.
@@ -0,0 +1 @@
1
+ export declare const downloadFromUrl: (source: string | Blob, filename?: string) => Promise<void>;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ 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;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.downloadFromUrl = void 0;
40
+ var downloadFromUrl = function (source, filename) { return __awaiter(void 0, void 0, void 0, function () {
41
+ var blob, res, urlObj, a, err_1;
42
+ var _a;
43
+ return __generator(this, function (_b) {
44
+ switch (_b.label) {
45
+ case 0:
46
+ _b.trys.push([0, 5, , 6]);
47
+ blob = void 0;
48
+ if (!(typeof source === 'string')) return [3 /*break*/, 3];
49
+ return [4 /*yield*/, fetch(source)];
50
+ case 1:
51
+ res = _b.sent();
52
+ if (!res.ok)
53
+ throw new Error("Failed to fetch file: ".concat(res.status));
54
+ return [4 /*yield*/, res.blob()];
55
+ case 2:
56
+ blob = _b.sent();
57
+ return [3 /*break*/, 4];
58
+ case 3:
59
+ blob = source;
60
+ _b.label = 4;
61
+ case 4:
62
+ urlObj = URL.createObjectURL(blob);
63
+ a = document.createElement('a');
64
+ a.href = urlObj;
65
+ a.download =
66
+ filename !== null && filename !== void 0 ? filename : (typeof source === 'string'
67
+ ? ((_a = source.split('/').pop()) !== null && _a !== void 0 ? _a : 'download')
68
+ : 'download');
69
+ document.body.appendChild(a);
70
+ a.click();
71
+ a.remove();
72
+ URL.revokeObjectURL(urlObj);
73
+ return [3 /*break*/, 6];
74
+ case 5:
75
+ err_1 = _b.sent();
76
+ console.error('downloadFromUrl error:', err_1);
77
+ return [3 /*break*/, 6];
78
+ case 6: return [2 /*return*/];
79
+ }
80
+ });
81
+ }); };
82
+ exports.downloadFromUrl = downloadFromUrl;
@@ -3,8 +3,9 @@ export interface FetchDataParams {
3
3
  url: string;
4
4
  method?: API_METHODS;
5
5
  body?: string;
6
+ headers?: Record<string, string>;
6
7
  }
7
- export declare const fetchData: ({ url, method, body, }: FetchDataParams) => Promise<{
8
+ export declare const fetchData: ({ url, method, body, headers, }: FetchDataParams) => Promise<{
8
9
  data: any | undefined;
9
10
  error: Error | undefined;
10
11
  }>;
@@ -51,12 +51,12 @@ exports.fetchData = void 0;
51
51
  var api_methods_1 = require("../constants/api-methods");
52
52
  var fetchData = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
53
53
  var data, error, res, err_1;
54
- var url = _b.url, _c = _b.method, method = _c === void 0 ? api_methods_1.API_METHODS.GET : _c, body = _b.body;
54
+ var url = _b.url, _c = _b.method, method = _c === void 0 ? api_methods_1.API_METHODS.GET : _c, body = _b.body, headers = _b.headers;
55
55
  return __generator(this, function (_d) {
56
56
  switch (_d.label) {
57
57
  case 0:
58
58
  _d.trys.push([0, 3, , 4]);
59
- return [4 /*yield*/, fetch(url, __assign({ method: method }, (method !== api_methods_1.API_METHODS.GET && body && { body: body })))];
59
+ return [4 /*yield*/, fetch(url, __assign(__assign({ method: method }, (headers ? { headers: headers } : {})), (method !== api_methods_1.API_METHODS.GET && body && { body: body })))];
60
60
  case 1:
61
61
  res = _d.sent();
62
62
  return [4 /*yield*/, res.json()];
@@ -13,7 +13,9 @@
13
13
  * The main async helper `getCachedData` now accepts a single options object
14
14
  * (`GetCachedDataOptions`) which includes `config`, optional `searchQuery`,
15
15
  * `filters`, `pageLimit` and extra `params` for the list API. Module cache
16
- * wrappers should call `getCachedData({ config, searchQuery, filters, pageLimit, params })`.
16
+ * wrappers should call `getCachedData({ config, searchQuery, filters, pageLimit, params, headers })`.
17
+ * Both `getCachedData` and `getCachedSingleItem` accept an optional `headers`
18
+ * object which will be forwarded to the underlying `fetchData` calls.
17
19
  *
18
20
  * Organization:
19
21
  * - Types
@@ -31,6 +33,7 @@ interface CacheConfig {
31
33
  interface GetCachedDataOptions {
32
34
  config: CacheConfig;
33
35
  params?: Record<string, unknown>;
36
+ headers?: Record<string, string>;
34
37
  }
35
38
  interface ListResponse<T> {
36
39
  count: number;
@@ -117,7 +120,7 @@ export declare const getCachedSingleItemSync: <T>(cacheKey: string, expirationMs
117
120
  * const config = { cacheKey: LS_KEYS.WORKSPACE, apiUrl: '/api/workspace', responseKey: 'workspace' };
118
121
  * const workspace = await getCachedSingleItem<WorkspaceBE>(config, { subdomain: 'school1' });
119
122
  */
120
- export declare const getCachedSingleItem: <T>(config: CacheConfig, params?: Record<string, string>) => Promise<T | null>;
123
+ export declare const getCachedSingleItem: <T>(config: CacheConfig, params?: Record<string, string>, headers?: Record<string, string>) => Promise<T | null>;
121
124
  /**
122
125
  * Invalidate (remove) cache for a module
123
126
  * Useful after create/update/delete operations
@@ -14,7 +14,9 @@
14
14
  * The main async helper `getCachedData` now accepts a single options object
15
15
  * (`GetCachedDataOptions`) which includes `config`, optional `searchQuery`,
16
16
  * `filters`, `pageLimit` and extra `params` for the list API. Module cache
17
- * wrappers should call `getCachedData({ config, searchQuery, filters, pageLimit, params })`.
17
+ * wrappers should call `getCachedData({ config, searchQuery, filters, pageLimit, params, headers })`.
18
+ * Both `getCachedData` and `getCachedSingleItem` accept an optional `headers`
19
+ * object which will be forwarded to the underlying `fetchData` calls.
18
20
  *
19
21
  * Organization:
20
22
  * - Types
@@ -79,7 +81,9 @@ function isCachedArrayShape(v) {
79
81
  if (!v || typeof v !== 'object')
80
82
  return false;
81
83
  var o = v;
82
- return Array.isArray(o.items) && typeof o.cachedAt === 'string';
84
+ return (Array.isArray(o.items) &&
85
+ typeof o.cachedAt === 'string' &&
86
+ typeof o.count === 'number');
83
87
  }
84
88
  function isCachedMapShape(v) {
85
89
  if (!v || typeof v !== 'object')
@@ -162,12 +166,12 @@ exports.getCachedDataSync = getCachedDataSync;
162
166
  * const active = await getCachedData<UserBE>({ config, filters: { enabled: true }, pageLimit: 200 });
163
167
  */
164
168
  var getCachedData = function (opts) { return __awaiter(void 0, void 0, void 0, function () {
165
- var config, params, cacheKey, apiUrl, responseKey, expirationMs, fallBackPageLimit, fallBackCurrentPage, filters, searchQuery, paramsWithoutFilters_1, otherParams_1, queryObj_1, searchParams_1, response_1, items_1, raw, currentTime, cachedTime, ageInMs, cachedTime, ageInMs, itemsArray, paramsWithoutFilters_2, otherParams, queryObj, searchParams, response, itemsRaw, items, count, itemsMap, updatedCache, error_1;
169
+ var config, params, headers, cacheKey, apiUrl, responseKey, expirationMs, fallBackPageLimit, fallBackCurrentPage, filters, searchQuery, paramsWithoutFilters_1, otherParams_1, queryObj_1, searchParams_1, response_1, items_1, raw, currentTime, cachedTime, ageInMs, cachedTime, ageInMs, itemsArray, paramsWithoutFilters_2, otherParams, queryObj, searchParams, response, itemsRaw, items, count, shouldCache, itemsMap, updatedCache, error_1;
166
170
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
167
171
  return __generator(this, function (_m) {
168
172
  switch (_m.label) {
169
173
  case 0:
170
- config = opts.config, params = opts.params;
174
+ config = opts.config, params = opts.params, headers = opts.headers;
171
175
  cacheKey = config.cacheKey, apiUrl = config.apiUrl, responseKey = config.responseKey;
172
176
  expirationMs = (_a = config.expirationMs) !== null && _a !== void 0 ? _a : constants_1.ONE_DAY_IN_MS;
173
177
  fallBackPageLimit = (_c = (_b = params === null || params === void 0 ? void 0 : params.pageLimit) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : '100';
@@ -197,6 +201,7 @@ var getCachedData = function (opts) { return __awaiter(void 0, void 0, void 0, f
197
201
  return [4 /*yield*/, (0, fetch_data_1.fetchData)({
198
202
  url: "".concat(apiUrl, "?").concat(searchParams_1.toString()),
199
203
  method: constants_1.API_METHODS.GET,
204
+ headers: headers,
200
205
  })];
201
206
  case 2:
202
207
  response_1 = _m.sent();
@@ -238,17 +243,18 @@ var getCachedData = function (opts) { return __awaiter(void 0, void 0, void 0, f
238
243
  return [4 /*yield*/, (0, fetch_data_1.fetchData)({
239
244
  url: "".concat(apiUrl, "?").concat(searchParams.toString()),
240
245
  method: constants_1.API_METHODS.GET,
246
+ headers: headers,
241
247
  })];
242
248
  case 4:
243
249
  response = _m.sent();
244
- itemsRaw = (responseKey
245
- ? (_j = response === null || response === void 0 ? void 0 : response.data) === null || _j === void 0 ? void 0 : _j[responseKey]
246
- : ((_k = response === null || response === void 0 ? void 0 : response.data) === null || _k === void 0 ? void 0 : _k.items) || (response === null || response === void 0 ? void 0 : response.data)) || [];
250
+ itemsRaw = (responseKey ? (_j = response === null || response === void 0 ? void 0 : response.data) === null || _j === void 0 ? void 0 : _j[responseKey] : (_k = response === null || response === void 0 ? void 0 : response.data) === null || _k === void 0 ? void 0 : _k.items) ||
251
+ [];
247
252
  items = Array.isArray(itemsRaw)
248
253
  ? itemsRaw
249
254
  : [itemsRaw];
250
- count = ((_l = response === null || response === void 0 ? void 0 : response.data) === null || _l === void 0 ? void 0 : _l.count) || items.length;
251
- if (items.length > 0) {
255
+ count = (_l = response === null || response === void 0 ? void 0 : response.data) === null || _l === void 0 ? void 0 : _l.count;
256
+ shouldCache = Array.isArray(itemsRaw) && count && items.length > 0;
257
+ if (shouldCache) {
252
258
  itemsMap = items.reduce(function (acc, item, idx) {
253
259
  var _a, _b;
254
260
  var obj = item;
@@ -260,10 +266,15 @@ var getCachedData = function (opts) { return __awaiter(void 0, void 0, void 0, f
260
266
  updatedCache = {
261
267
  items: itemsMap,
262
268
  cachedAt: new Date().toISOString(),
269
+ count: count,
263
270
  };
264
271
  (0, local_storage_1.setStorageValue)(cacheKey, updatedCache);
265
272
  }
266
- return [2 /*return*/, { count: count, items: items }];
273
+ // Return count as number when present, otherwise fallback to items.length
274
+ return [2 /*return*/, {
275
+ count: count,
276
+ items: items,
277
+ }];
267
278
  case 5:
268
279
  error_1 = _m.sent();
269
280
  console.error("Error fetching data for ".concat(cacheKey, ":"), error_1);
@@ -359,7 +370,7 @@ exports.getCachedSingleItemSync = getCachedSingleItemSync;
359
370
  * const config = { cacheKey: LS_KEYS.WORKSPACE, apiUrl: '/api/workspace', responseKey: 'workspace' };
360
371
  * const workspace = await getCachedSingleItem<WorkspaceBE>(config, { subdomain: 'school1' });
361
372
  */
362
- var getCachedSingleItem = function (config, params) { return __awaiter(void 0, void 0, void 0, function () {
373
+ var getCachedSingleItem = function (config, params, headers) { return __awaiter(void 0, void 0, void 0, function () {
363
374
  var cacheKey, apiUrl, expirationMs, cachedData, currentTime, cachedTime, ageInMs, queryParams, response, item, updatedCache, error_2;
364
375
  var _a;
365
376
  return __generator(this, function (_b) {
@@ -385,6 +396,7 @@ var getCachedSingleItem = function (config, params) { return __awaiter(void 0, v
385
396
  return [4 /*yield*/, (0, fetch_data_1.fetchData)({
386
397
  url: "".concat(apiUrl).concat(queryParams),
387
398
  method: constants_1.API_METHODS.GET,
399
+ headers: headers,
388
400
  })];
389
401
  case 2:
390
402
  response = _b.sent();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-pakistan/util-functions",
3
- "version": "1.25.19",
3
+ "version": "1.25.21",
4
4
  "description": "A library of all util functions",
5
5
  "main": "index.js",
6
6
  "scripts": {