@selkirk-systems/fetch 1.5.1 → 1.7.0

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/Fetch.js CHANGED
@@ -1,9 +1,7 @@
1
1
  //Inspired by https://www.bennadel.com/blog/4180-canceling-api-requests-using-fetch-and-abortcontroller-in-javascript.htm
2
2
 
3
3
  import Download from './Download';
4
- import { DELETE_FROM_CACHE, UPDATE_CACHE } from './constants/FetchConstants';
5
4
  import FetchErrorHandler from './middleware/FetchErrorHandler';
6
- import { dispatch, serializeData } from "@selkirk-systems/state-management";
7
5
 
8
6
  // Regular expression patterns for testing content-type response headers.
9
7
  const RE_CONTENT_TYPE_JSON = /^application\/(x-)?json/i;
@@ -15,9 +13,6 @@ const CONTENT_TYPE_DOWNLOADS = {
15
13
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true
16
14
  };
17
15
 
18
- //30 minutes
19
- const CACHED_EXPIRY_TIMESTAMP = 30 * 60000;
20
-
21
16
  //We store the original promise.catch so we can override it in some
22
17
  //scenarios when we want to swallow errors vs bubble them up.
23
18
  const ORIGINAL_CATCH_FN = Promise.prototype.catch;
@@ -39,17 +34,6 @@ export function applyMiddleware(middleware = []) {
39
34
  _middlewares = middleware;
40
35
  _middlewares.push(FetchErrorHandler);
41
36
  }
42
- export function OnOKResponse(fn) {
43
- return ([network, isAbort]) => {
44
- //Is any status is outside 200 - 299 it is not ok
45
- if (network.status.code < 200 || network.status.code >= 300 || isAbort) {
46
- return [network, isAbort];
47
- }
48
-
49
- //Run the function since its all ok
50
- return fn([network, isAbort]);
51
- };
52
- }
53
37
  function isServiceWorker() {
54
38
  return self;
55
39
  }
@@ -265,7 +249,7 @@ function _applyMiddleware(err, response, options) {
265
249
  * Unwrap the response payload from the given response based on the reported
266
250
  * content-type.
267
251
  */
268
- async function unwrapResponseData(response) {
252
+ export async function unwrapResponseData(response) {
269
253
  var contentType = response.headers.has("content-type") ? response.headers.get("content-type") : "";
270
254
  if (RE_CONTENT_TYPE_JSON.test(contentType)) {
271
255
  return response.json();
@@ -421,311 +405,4 @@ function normalizeTransportError(transportError, request, config) {
421
405
  }
422
406
  };
423
407
  }
424
- const responseObjectJson = {
425
- status: 200,
426
- headers: {
427
- 'Content-Type': 'application/json'
428
- }
429
- };
430
- export const getCacheByName = async name => {
431
- try {
432
- return caches.open(name);
433
- } catch (err) {
434
- throw err;
435
- }
436
- };
437
- export const putJsonInCache = (cache, url, json) => {
438
- const response = new Response(JSON.stringify(json), responseObjectJson);
439
- return cache.put(url, response);
440
- };
441
- const _caches = {};
442
- const _updatingCache = {};
443
- const DATA_METHODS = {
444
- "GET": null,
445
- "PATCH": null,
446
- "POST": null,
447
- "PUT": null
448
- };
449
- const _fetch = (url, options = {}) => {
450
- const cacheName = getCacheNameFromUrl(url);
451
-
452
- //HANDLE: Service worker BS, environment is different don't cache if were in a service worker.
453
- if (!self || !cacheName) {
454
- return Fetch(url, options);
455
- }
456
- let _cache = _caches[cacheName];
457
- async function cacheResponse([response, isAbort]) {
458
- const status = response.status.code;
459
- const headers = response.request.headers;
460
- const method = response.request.method;
461
- if (status >= 200 && status < 400 && headers.get('content-type') === "application/json") {
462
- if (DATA_METHODS.hasOwnProperty(method)) {
463
- const data = serializeData(response.data);
464
-
465
- //HANDLE: List/Array like responses
466
- if (data.page && !data.items || data.items && data.items.length === 0) {
467
- deleteFromCache(_cache, url, response);
468
- return [response, isAbort];
469
- }
470
-
471
- //HANDLE: Record like response
472
- if (data.id) {
473
- let uuid = getUUID(url.toString());
474
- let matchOptions = {};
475
- if (method === "POST") {
476
- uuid = {
477
- id: data.id,
478
- shortPath: url.toString()
479
- };
480
- }
481
-
482
- /**
483
- * POST new records are hard, what cached list do we put the new record in? what about sort? blag. Don't have a good answer yet
484
- * For now, new records will be put in the first cached entry that matches at the 0 index, this 'should' be page=0 cached entries
485
- * and the records should all show up in UI at the top. This is the most common UX for adding records to a list,
486
- * one day some how figure out a less fragile robust method.
487
- *
488
- * Perhaps we should just refetch all the matched cache urls... but this could be huge and slow and network heavy...
489
- */
490
- await cacheFindAllLike({
491
- cache: _cache,
492
- url: uuid.shortPath,
493
- property: "id",
494
- value: data.id,
495
- method: method
496
- }).then(async matches => {
497
- if (matches.length) {
498
- const finalOptions = {
499
- ...responseObjectJson
500
- };
501
- finalOptions.headers['Time-Cached'] = new Date().getTime();
502
- await matches.forEach(async match => {
503
- const items = extractDataArray(match.data);
504
-
505
- //This is where we put the new record on the top of the cached list, even if a new network request would place it somewhere
506
- // else based on sort etc.
507
- if (method === "POST") {
508
- items.unshift(data);
509
- } else {
510
- items[match.matchIndex] = data;
511
- }
512
- const responseObj = new Response(JSON.stringify(match.data), finalOptions);
513
- dispatch(UPDATE_CACHE, {
514
- url: new URL(match.request.url),
515
- response: match.response
516
- });
517
- return _cache.put(match.request.url, responseObj);
518
- });
519
- }
520
- });
521
- return [response, isAbort];
522
- }
523
- const finalOptions = {
524
- ...responseObjectJson
525
- };
526
- finalOptions.headers['Time-Cached'] = new Date().getTime();
527
- const responseObj = new Response(JSON.stringify(response.data), finalOptions);
528
- _cache.put(url, responseObj);
529
- dispatch(UPDATE_CACHE, {
530
- url: url,
531
- response: response
532
- });
533
- return [response, isAbort];
534
- }
535
- if (method === "DELETE") {
536
- deleteFromCache(_cache, url, response);
537
- return [response, isAbort];
538
- }
539
- }
540
- return [response, isAbort];
541
- }
542
- function cacheMatch() {
543
- //HANDLE: Data updates, always return fresh data
544
- if (options.skipCache || options.method && DATA_METHODS.hasOwnProperty(options.method)) {
545
- return Fetch(url, options).then(cacheResponse);
546
- }
547
- const uuid = getUUID(url.toString());
548
-
549
- //HANDLE: individual records, if we are looking for a record check cache for any array or search results with this record
550
- if (uuid.id) {
551
- return cacheFindLike({
552
- cache: _cache,
553
- url: uuid.shortPath,
554
- property: "id",
555
- value: uuid.id
556
- }).then(match => {
557
- if (match) {
558
- //Behind the scenes still fetch the record and update the cache but don't make the user wait for it.
559
- Fetch(url, options).then(cacheResponse);
560
- const responseObj = new Response(JSON.stringify(match.match));
561
- return Promise.resolve([{
562
- request: null,
563
- response: responseObj,
564
- data: match.match,
565
- status: {
566
- code: 200,
567
- text: '',
568
- isAbort: false
569
- }
570
- }, false]);
571
- }
572
- return Fetch(url, options).then(cacheResponse);
573
- });
574
- }
575
- return _cache.match(url).then(response => {
576
- if (response) {
577
- const timeCached = response.headers.get('Time-Cached');
578
- if (expiredCache(timeCached)) {
579
- _cache.delete(url);
580
- return Fetch(url, options).then(cacheResponse);
581
- }
582
- return unwrapResponseData(response).then(obj => {
583
- Fetch(url, options).then(cacheResponse);
584
- return Promise.resolve([{
585
- request: null,
586
- response: response,
587
- data: obj,
588
- status: {
589
- code: response.status,
590
- text: response.statusText,
591
- isAbort: false
592
- }
593
- }, false]);
594
- });
595
- }
596
- return Fetch(url, options).then(cacheResponse);
597
- });
598
- }
599
- if (_cache) {
600
- return cacheMatch();
601
- }
602
- return caches.open(cacheName).then(cache => {
603
- _caches[cacheName] = cache;
604
- _cache = cache;
605
- }).then(cacheMatch);
606
- };
607
- function deleteFromCache(_cache, url, response) {
608
- _cache.delete(url);
609
- dispatch(DELETE_FROM_CACHE, {
610
- url: url,
611
- response: response
612
- });
613
- }
614
- function cacheFindAllLike(options) {
615
- const finalOptions = {
616
- ...options,
617
- findAll: true
618
- };
619
- return cacheFindLike(finalOptions);
620
- }
621
- function cacheFindLike(options) {
622
- const cache = options.cache;
623
- const url = options.url;
624
- const property = options.property;
625
- const value = options.value;
626
- const findAll = options.findAll;
627
- const matchOptions = options.matchOptions;
628
- const method = options.method || "GET";
629
- return cache.keys().then(keys => {
630
- const matchingRequests = [];
631
- for (let i = 0; i < keys.length; i++) {
632
- const request = keys[i];
633
- if (looksLikeResultListUrl(request.url, url)) {
634
- matchingRequests.push(cache.match(request, matchOptions).then(match => {
635
- match._request = request;
636
- return match;
637
- }));
638
- }
639
- }
640
- return Promise.all(matchingRequests).then(responses => {
641
- let count = 0;
642
- const ret = [];
643
- const checkCache = async index => {
644
- if (index >= responses.length) return ret;
645
- return serializeResponse(responses[index]).then(json => {
646
- const items = extractDataArray(json);
647
- const response = responses[count];
648
- const retObj = {
649
- request: response._request,
650
- response: response,
651
- data: json,
652
- match: json,
653
- matchIndex: -1,
654
- status: {
655
- code: response.status,
656
- text: response.statusText,
657
- isAbort: false
658
- }
659
- };
660
- if (method === "POST") {
661
- return findAll ? [retObj] : retObj;
662
- }
663
- const matchIndex = items.findIndex(item => item[property] === value);
664
- count++;
665
- if (matchIndex >= 0) {
666
- retObj.match = items[matchIndex];
667
- retObj.matchIndex = matchIndex;
668
- if (!findAll) {
669
- return retObj;
670
- } else {
671
- ret.push(retObj);
672
- }
673
- return checkCache(count);
674
- }
675
- if (count >= responses.length) {
676
- return findAll ? ret : null;
677
- }
678
- return checkCache(count);
679
- });
680
- };
681
- if (!responses || !responses.length) return findAll ? ret : null;
682
- return checkCache(count);
683
- });
684
- });
685
- }
686
-
687
- /**
688
- * Check if request.url looks like a list result type url, if it contains a UUID it is likely not.
689
- * @param {*} requestURL
690
- * @param {*} matchURL
691
- * @returns
692
- */
693
- function looksLikeResultListUrl(requestURL, matchURL) {
694
- const uuid = getUUID(requestURL.toString());
695
- return !uuid.id && requestURL.indexOf(matchURL) >= 0;
696
- }
697
- function extractDataArray(obj) {
698
- for (var prop in obj._embedded) {
699
- if (!obj._embedded.hasOwnProperty(prop)) continue;
700
- return obj._embedded[prop];
701
- }
702
- return [obj];
703
- }
704
- async function serializeResponse(response) {
705
- return response.text().then(data => {
706
- return JSON.parse(data);
707
- });
708
- }
709
- function getUUID(str) {
710
- const UUID_REG_EXP = /.+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}).*?/;
711
- const match = UUID_REG_EXP.exec(str);
712
- let id, shortPath;
713
- if (match && match[1]) {
714
- id = match[1];
715
- shortPath = str.split(`/${id}`)[0];
716
- }
717
- return {
718
- id: id,
719
- shortPath: shortPath
720
- };
721
- }
722
- function getCacheNameFromUrl(url) {
723
- const API_REG_EXP = /p\/.+com\/(.*?)\//;
724
- const matchArray = url.toString().match(API_REG_EXP);
725
- return matchArray && matchArray.length >= 1 ? matchArray[1] : null;
726
- }
727
- function expiredCache(timeCached) {
728
- const now = new Date().getTime();
729
- return Math.abs(now - timeCached) >= CACHED_EXPIRY_TIMESTAMP;
730
- }
731
- export default _fetch;
408
+ export default Fetch;
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { default as Download } from './Download';
2
- export { default as fetch, applyMiddleware, OnOKResponse } from './Fetch';
2
+ export { default as fetch, applyMiddleware } from './Fetch';
3
+ export { default as CacheAPI } from './middleware/CacheAPI';
3
4
  export * from "./utils/FetchUtils";
4
5
  export * from "./constants/FetchConstants";
@@ -0,0 +1,302 @@
1
+ import { unwrapResponseData } from '../Fetch';
2
+ import { DELETE_FROM_CACHE, UPDATE_CACHE } from '../constants/FetchConstants';
3
+ import { dispatch, serializeData } from "@selkirk-systems/state-management";
4
+
5
+ //30 minutes
6
+ const CACHED_EXPIRY_TIMESTAMP = 30 * 60000;
7
+ const _caches = {};
8
+ const DATA_METHODS = {
9
+ "GET": null,
10
+ "PATCH": null,
11
+ "POST": null,
12
+ "PUT": null
13
+ };
14
+ const responseObjectJson = {
15
+ status: 200,
16
+ headers: {
17
+ 'Content-Type': 'application/json'
18
+ }
19
+ };
20
+ const CacheAPI = Fetch => (url, options = {}) => {
21
+ const cacheName = getCacheNameFromUrl(url);
22
+
23
+ //HANDLE: Service worker BS, environment is different don't cache if were in a service worker.
24
+ if (!self || !cacheName) {
25
+ return Fetch(url, options);
26
+ }
27
+ let _cache = _caches[cacheName];
28
+ async function cacheResponse([response, isAbort]) {
29
+ const status = response.status.code;
30
+ const headers = response.request.headers;
31
+ const method = response.request.method;
32
+ if (status >= 200 && status < 400 && headers.get('content-type') === "application/json") {
33
+ if (DATA_METHODS.hasOwnProperty(method)) {
34
+ const data = serializeData(response.data);
35
+
36
+ //HANDLE: List/Array like responses
37
+ if (data.page && !data.items || data.items && data.items.length === 0) {
38
+ deleteFromCache(_cache, url, response);
39
+ return [response, isAbort];
40
+ }
41
+
42
+ //HANDLE: Record like response
43
+ if (data.id) {
44
+ let uuid = getUUID(url.toString());
45
+ let matchOptions = {};
46
+ if (method === "POST") {
47
+ uuid = {
48
+ id: data.id,
49
+ shortPath: url.toString()
50
+ };
51
+ }
52
+
53
+ /**
54
+ * POST new records are hard, what cached list do we put the new record in? what about sort? blag. Don't have a good answer yet
55
+ * For now, new records will be put in the first cached entry that matches at the 0 index, this 'should' be page=0 cached entries
56
+ * and the records should all show up in UI at the top. This is the most common UX for adding records to a list,
57
+ * one day some how figure out a less fragile robust method.
58
+ *
59
+ * Perhaps we should just refetch all the matched cache urls... but this could be huge and slow and network heavy...
60
+ */
61
+ await cacheFindAllLike({
62
+ cache: _cache,
63
+ url: uuid.shortPath,
64
+ property: "id",
65
+ value: data.id,
66
+ method: method
67
+ }).then(async matches => {
68
+ if (matches.length) {
69
+ const finalOptions = {
70
+ ...responseObjectJson
71
+ };
72
+ finalOptions.headers['Time-Cached'] = new Date().getTime();
73
+ await matches.forEach(async match => {
74
+ const items = extractDataArray(match.data);
75
+
76
+ //This is where we put the new record on the top of the cached list, even if a new network request would place it somewhere
77
+ // else based on sort etc.
78
+ if (method === "POST") {
79
+ items.unshift(data);
80
+ } else {
81
+ items[match.matchIndex] = data;
82
+ }
83
+ const responseObj = new Response(JSON.stringify(match.data), finalOptions);
84
+ dispatch(UPDATE_CACHE, {
85
+ url: new URL(match.request.url),
86
+ response: match.response
87
+ });
88
+ return _cache.put(match.request.url, responseObj);
89
+ });
90
+ }
91
+ });
92
+ return [response, isAbort];
93
+ }
94
+ const finalOptions = {
95
+ ...responseObjectJson
96
+ };
97
+ finalOptions.headers['Time-Cached'] = new Date().getTime();
98
+ const responseObj = new Response(JSON.stringify(response.data), finalOptions);
99
+ _cache.put(url, responseObj);
100
+ dispatch(UPDATE_CACHE, {
101
+ url: url,
102
+ response: response
103
+ });
104
+ return [response, isAbort];
105
+ }
106
+ if (method === "DELETE") {
107
+ deleteFromCache(_cache, url, response);
108
+ return [response, isAbort];
109
+ }
110
+ }
111
+ return [response, isAbort];
112
+ }
113
+ function cacheMatch() {
114
+ //HANDLE: Data updates, always return fresh data
115
+ if (options.skipCache || options.method && DATA_METHODS.hasOwnProperty(options.method)) {
116
+ return Fetch(url, options).then(cacheResponse);
117
+ }
118
+ const uuid = getUUID(url.toString());
119
+
120
+ //HANDLE: individual records, if we are looking for a record check cache for any array or search results with this record
121
+ if (uuid.id) {
122
+ return cacheFindLike({
123
+ cache: _cache,
124
+ url: uuid.shortPath,
125
+ property: "id",
126
+ value: uuid.id
127
+ }).then(match => {
128
+ if (match) {
129
+ //Behind the scenes still fetch the record and update the cache but don't make the user wait for it.
130
+ Fetch(url, options).then(cacheResponse);
131
+ const responseObj = new Response(JSON.stringify(match.match));
132
+ return Promise.resolve([{
133
+ request: null,
134
+ response: responseObj,
135
+ data: match.match,
136
+ status: {
137
+ code: 200,
138
+ text: '',
139
+ isAbort: false
140
+ }
141
+ }, false]);
142
+ }
143
+ return Fetch(url, options).then(cacheResponse);
144
+ });
145
+ }
146
+ return _cache.match(url).then(response => {
147
+ if (response) {
148
+ const timeCached = response.headers.get('Time-Cached');
149
+ if (expiredCache(timeCached)) {
150
+ _cache.delete(url);
151
+ return Fetch(url, options).then(cacheResponse);
152
+ }
153
+ return unwrapResponseData(response).then(obj => {
154
+ Fetch(url, options).then(cacheResponse);
155
+ return Promise.resolve([{
156
+ request: null,
157
+ response: response,
158
+ data: obj,
159
+ status: {
160
+ code: response.status,
161
+ text: response.statusText,
162
+ isAbort: false
163
+ }
164
+ }, false]);
165
+ });
166
+ }
167
+ return Fetch(url, options).then(cacheResponse);
168
+ });
169
+ }
170
+ if (_cache) {
171
+ return cacheMatch();
172
+ }
173
+ return caches.open(cacheName).then(cache => {
174
+ _caches[cacheName] = cache;
175
+ _cache = cache;
176
+ }).then(cacheMatch);
177
+ };
178
+ function deleteFromCache(_cache, url, response) {
179
+ _cache.delete(url);
180
+ dispatch(DELETE_FROM_CACHE, {
181
+ url: url,
182
+ response: response
183
+ });
184
+ }
185
+ function cacheFindAllLike(options) {
186
+ const finalOptions = {
187
+ ...options,
188
+ findAll: true
189
+ };
190
+ return cacheFindLike(finalOptions);
191
+ }
192
+ function cacheFindLike(options) {
193
+ const cache = options.cache;
194
+ const url = options.url;
195
+ const property = options.property;
196
+ const value = options.value;
197
+ const findAll = options.findAll;
198
+ const matchOptions = options.matchOptions;
199
+ const method = options.method || "GET";
200
+ return cache.keys().then(keys => {
201
+ const matchingRequests = [];
202
+ for (let i = 0; i < keys.length; i++) {
203
+ const request = keys[i];
204
+ if (looksLikeResultListUrl(request.url, url)) {
205
+ matchingRequests.push(cache.match(request, matchOptions).then(match => {
206
+ match._request = request;
207
+ return match;
208
+ }));
209
+ }
210
+ }
211
+ return Promise.all(matchingRequests).then(responses => {
212
+ let count = 0;
213
+ const ret = [];
214
+ const checkCache = async index => {
215
+ if (index >= responses.length) return ret;
216
+ return serializeResponse(responses[index]).then(json => {
217
+ const items = extractDataArray(json);
218
+ const response = responses[count];
219
+ const retObj = {
220
+ request: response._request,
221
+ response: response,
222
+ data: json,
223
+ match: json,
224
+ matchIndex: -1,
225
+ status: {
226
+ code: response.status,
227
+ text: response.statusText,
228
+ isAbort: false
229
+ }
230
+ };
231
+ if (method === "POST") {
232
+ return findAll ? [retObj] : retObj;
233
+ }
234
+ const matchIndex = items.findIndex(item => item[property] === value);
235
+ count++;
236
+ if (matchIndex >= 0) {
237
+ retObj.match = items[matchIndex];
238
+ retObj.matchIndex = matchIndex;
239
+ if (!findAll) {
240
+ return retObj;
241
+ } else {
242
+ ret.push(retObj);
243
+ }
244
+ return checkCache(count);
245
+ }
246
+ if (count >= responses.length) {
247
+ return findAll ? ret : null;
248
+ }
249
+ return checkCache(count);
250
+ });
251
+ };
252
+ if (!responses || !responses.length) return findAll ? ret : null;
253
+ return checkCache(count);
254
+ });
255
+ });
256
+ }
257
+
258
+ /**
259
+ * Check if request.url looks like a list result type url, if it contains a UUID it is likely not.
260
+ * @param {*} requestURL
261
+ * @param {*} matchURL
262
+ * @returns
263
+ */
264
+ function looksLikeResultListUrl(requestURL, matchURL) {
265
+ const uuid = getUUID(requestURL.toString());
266
+ return !uuid.id && requestURL.indexOf(matchURL) >= 0;
267
+ }
268
+ function extractDataArray(obj) {
269
+ for (var prop in obj._embedded) {
270
+ if (!obj._embedded.hasOwnProperty(prop)) continue;
271
+ return obj._embedded[prop];
272
+ }
273
+ return [obj];
274
+ }
275
+ async function serializeResponse(response) {
276
+ return response.text().then(data => {
277
+ return JSON.parse(data);
278
+ });
279
+ }
280
+ function getUUID(str) {
281
+ const UUID_REG_EXP = /.+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}).*?/;
282
+ const match = UUID_REG_EXP.exec(str);
283
+ let id, shortPath;
284
+ if (match && match[1]) {
285
+ id = match[1];
286
+ shortPath = str.split(`/${id}`)[0];
287
+ }
288
+ return {
289
+ id: id,
290
+ shortPath: shortPath
291
+ };
292
+ }
293
+ function getCacheNameFromUrl(url) {
294
+ const API_REG_EXP = /p\/.+com\/(.*?)\//;
295
+ const matchArray = url.toString().match(API_REG_EXP);
296
+ return matchArray && matchArray.length >= 1 ? matchArray[1] : null;
297
+ }
298
+ function expiredCache(timeCached) {
299
+ const now = new Date().getTime();
300
+ return Math.abs(now - timeCached) >= CACHED_EXPIRY_TIMESTAMP;
301
+ }
302
+ export default CacheAPI;