@selkirk-systems/fetch 1.5.2 → 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.
@@ -0,0 +1,422 @@
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
+
8
+ const _caches = {};
9
+
10
+ const DATA_METHODS = {
11
+ "GET": null,
12
+ "PATCH": null,
13
+ "POST": null,
14
+ "PUT": null
15
+ }
16
+
17
+
18
+ const responseObjectJson = {
19
+ status: 200,
20
+ headers: {
21
+ 'Content-Type': 'application/json'
22
+ }
23
+ }
24
+
25
+ const CacheAPI = ( Fetch ) => ( url, options = {} ) => {
26
+
27
+
28
+ const cacheName = getCacheNameFromUrl( url );
29
+
30
+ //HANDLE: Service worker BS, environment is different don't cache if were in a service worker.
31
+ if ( !self || !cacheName ) {
32
+ return Fetch( url, options );
33
+ }
34
+
35
+ let _cache = _caches[cacheName];
36
+
37
+ async function cacheResponse( [response, isAbort] ) {
38
+
39
+ const status = response.status.code;
40
+ const headers = response.request.headers;
41
+ const method = response.request.method;
42
+
43
+
44
+ if ( status >= 200 && status < 400 && headers.get( 'content-type' ) === "application/json" ) {
45
+
46
+ if ( DATA_METHODS.hasOwnProperty( method ) ) {
47
+
48
+ const data = serializeData( response.data );
49
+
50
+ //HANDLE: List/Array like responses
51
+ if ( data.page && !data.items || data.items && data.items.length === 0 ) {
52
+
53
+ deleteFromCache( _cache, url, response );
54
+
55
+ return [response, isAbort];
56
+
57
+ }
58
+
59
+ //HANDLE: Record like response
60
+ if ( data.id ) {
61
+
62
+ let uuid = getUUID( url.toString() );
63
+ let matchOptions = {};
64
+
65
+ if ( method === "POST" ) {
66
+
67
+ uuid = {
68
+ id: data.id,
69
+ shortPath: url.toString()
70
+ }
71
+
72
+ }
73
+
74
+ /**
75
+ * 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
76
+ * 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
77
+ * and the records should all show up in UI at the top. This is the most common UX for adding records to a list,
78
+ * one day some how figure out a less fragile robust method.
79
+ *
80
+ * Perhaps we should just refetch all the matched cache urls... but this could be huge and slow and network heavy...
81
+ */
82
+ await cacheFindAllLike( { cache: _cache, url: uuid.shortPath, property: "id", value: data.id, method: method } )
83
+ .then( async ( matches ) => {
84
+
85
+ if ( matches.length ) {
86
+
87
+ const finalOptions = { ...responseObjectJson };
88
+ finalOptions.headers['Time-Cached'] = new Date().getTime();
89
+
90
+ await matches.forEach( async match => {
91
+
92
+ const items = extractDataArray( match.data );
93
+
94
+ //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
95
+ // else based on sort etc.
96
+ if ( method === "POST" ) {
97
+ items.unshift( data );
98
+ }
99
+ else {
100
+ items[match.matchIndex] = data;
101
+ }
102
+
103
+ const responseObj = new Response( JSON.stringify( match.data ), finalOptions );
104
+
105
+ dispatch( UPDATE_CACHE, { url: new URL( match.request.url ), response: match.response } );
106
+
107
+ return _cache.put( match.request.url, responseObj );
108
+
109
+ } )
110
+
111
+ }
112
+ } )
113
+
114
+ return [response, isAbort];
115
+
116
+ }
117
+
118
+ const finalOptions = { ...responseObjectJson };
119
+ finalOptions.headers['Time-Cached'] = new Date().getTime();
120
+
121
+ const responseObj = new Response( JSON.stringify( response.data ), finalOptions );
122
+ _cache.put( url, responseObj );
123
+
124
+ dispatch( UPDATE_CACHE, { url: url, response: response } );
125
+
126
+ return [response, isAbort];
127
+ }
128
+
129
+ if ( method === "DELETE" ) {
130
+
131
+ deleteFromCache( _cache, url, response );
132
+ return [response, isAbort];
133
+
134
+ }
135
+
136
+
137
+ }
138
+
139
+ return [response, isAbort];
140
+
141
+ }
142
+
143
+ function cacheMatch() {
144
+
145
+ //HANDLE: Data updates, always return fresh data
146
+ if ( options.skipCache || options.method && DATA_METHODS.hasOwnProperty( options.method ) ) {
147
+
148
+ return Fetch( url, options ).then( cacheResponse );
149
+
150
+ }
151
+
152
+ const uuid = getUUID( url.toString() );
153
+
154
+ //HANDLE: individual records, if we are looking for a record check cache for any array or search results with this record
155
+ if ( uuid.id ) {
156
+
157
+ return cacheFindLike( { cache: _cache, url: uuid.shortPath, property: "id", value: uuid.id } ).then( ( match ) => {
158
+
159
+ if ( match ) {
160
+
161
+ //Behind the scenes still fetch the record and update the cache but don't make the user wait for it.
162
+ Fetch( url, options ).then( cacheResponse );
163
+
164
+ const responseObj = new Response( JSON.stringify( match.match ) );
165
+
166
+ return Promise.resolve( [{
167
+ request: null,
168
+ response: responseObj,
169
+ data: match.match,
170
+ status: {
171
+ code: 200,
172
+ text: '',
173
+ isAbort: false
174
+ },
175
+ }, false] )
176
+ }
177
+
178
+
179
+ return Fetch( url, options ).then( cacheResponse );
180
+
181
+ } )
182
+
183
+ }
184
+
185
+
186
+ return _cache.match( url ).then( ( response ) => {
187
+
188
+ if ( response ) {
189
+
190
+ const timeCached = response.headers.get( 'Time-Cached' );
191
+
192
+ if ( expiredCache( timeCached ) ) {
193
+
194
+ _cache.delete( url );
195
+ return Fetch( url, options ).then( cacheResponse );
196
+
197
+ }
198
+
199
+ return unwrapResponseData( response ).then( ( obj ) => {
200
+ Fetch( url, options ).then( cacheResponse )
201
+ return Promise.resolve( [{
202
+ request: null,
203
+ response: response,
204
+ data: obj,
205
+ status: {
206
+ code: response.status,
207
+ text: response.statusText,
208
+ isAbort: false
209
+ },
210
+ }, false] )
211
+ } )
212
+
213
+
214
+ }
215
+
216
+ return Fetch( url, options ).then( cacheResponse );
217
+ } )
218
+ }
219
+
220
+
221
+
222
+ if ( _cache ) {
223
+ return cacheMatch()
224
+ }
225
+
226
+
227
+ return caches.open( cacheName ).then( ( cache ) => {
228
+ _caches[cacheName] = cache;
229
+ _cache = cache;
230
+ } ).then( cacheMatch )
231
+
232
+ }
233
+
234
+
235
+ function deleteFromCache( _cache, url, response ) {
236
+
237
+ _cache.delete( url );
238
+ dispatch( DELETE_FROM_CACHE, { url: url, response: response } );
239
+
240
+ }
241
+
242
+ function cacheFindAllLike( options ) {
243
+
244
+ const finalOptions = {
245
+ ...options,
246
+ findAll: true
247
+ }
248
+
249
+ return cacheFindLike( finalOptions );
250
+ }
251
+
252
+ function cacheFindLike( options ) {
253
+
254
+ const cache = options.cache;
255
+ const url = options.url;
256
+ const property = options.property;
257
+ const value = options.value;
258
+ const findAll = options.findAll;
259
+ const matchOptions = options.matchOptions
260
+ const method = options.method || "GET";
261
+
262
+ return cache.keys().then( ( keys ) => {
263
+
264
+ const matchingRequests = [];
265
+
266
+ for ( let i = 0; i < keys.length; i++ ) {
267
+
268
+ const request = keys[i];
269
+
270
+ if ( looksLikeResultListUrl( request.url, url ) ) {
271
+
272
+ matchingRequests.push( cache.match( request, matchOptions ).then( ( match ) => {
273
+
274
+ match._request = request;
275
+
276
+ return match;
277
+ } ) )
278
+
279
+ }
280
+
281
+ }
282
+
283
+ return Promise.all( matchingRequests ).then( ( responses ) => {
284
+ let count = 0;
285
+
286
+ const ret = [];
287
+
288
+ const checkCache = async ( index ) => {
289
+
290
+ if ( index >= responses.length ) return ret;
291
+
292
+ return serializeResponse( responses[index] ).then( json => {
293
+
294
+ const items = extractDataArray( json );
295
+ const response = responses[count];
296
+
297
+ const retObj = {
298
+ request: response._request,
299
+ response: response,
300
+ data: json,
301
+ match: json,
302
+ matchIndex: -1,
303
+ status: {
304
+ code: response.status,
305
+ text: response.statusText,
306
+ isAbort: false
307
+ }
308
+ }
309
+
310
+ if ( method === "POST" ) {
311
+ return findAll ? [retObj] : retObj;
312
+ }
313
+
314
+ const matchIndex = items.findIndex( item => item[property] === value );
315
+
316
+ count++;
317
+
318
+ if ( matchIndex >= 0 ) {
319
+
320
+ retObj.match = items[matchIndex];
321
+ retObj.matchIndex = matchIndex;
322
+
323
+ if ( !findAll ) {
324
+ return retObj;
325
+ }
326
+ else {
327
+ ret.push( retObj );
328
+ }
329
+
330
+ return checkCache( count );
331
+ }
332
+
333
+
334
+ if ( count >= responses.length ) {
335
+ return findAll ? ret : null;
336
+ }
337
+
338
+ return checkCache( count );
339
+
340
+ } )
341
+ }
342
+
343
+ if ( !responses || !responses.length ) return findAll ? ret : null;
344
+
345
+ return checkCache( count );
346
+ } )
347
+ } );
348
+
349
+
350
+ }
351
+
352
+ /**
353
+ * Check if request.url looks like a list result type url, if it contains a UUID it is likely not.
354
+ * @param {*} requestURL
355
+ * @param {*} matchURL
356
+ * @returns
357
+ */
358
+ function looksLikeResultListUrl( requestURL, matchURL ) {
359
+
360
+ const uuid = getUUID( requestURL.toString() );
361
+
362
+ return !uuid.id && requestURL.indexOf( matchURL ) >= 0;
363
+ }
364
+
365
+
366
+ function extractDataArray( obj ) {
367
+ for ( var prop in obj._embedded ) {
368
+ if ( !obj._embedded.hasOwnProperty( prop ) ) continue;
369
+ return obj._embedded[prop];
370
+ }
371
+
372
+ return [obj];
373
+ }
374
+
375
+ async function serializeResponse( response ) {
376
+
377
+ return response.text().then( data => {
378
+ return JSON.parse( data );
379
+ } )
380
+
381
+ }
382
+
383
+ function getUUID( str ) {
384
+
385
+ const UUID_REG_EXP = /.+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}).*?/;
386
+ const match = UUID_REG_EXP.exec( str );
387
+
388
+ let id, shortPath;
389
+
390
+ if ( match && match[1] ) {
391
+ id = match[1];
392
+ shortPath = str.split( `/${id}` )[0];
393
+ }
394
+
395
+ return {
396
+ id: id,
397
+ shortPath: shortPath
398
+ }
399
+
400
+ }
401
+
402
+
403
+
404
+ function getCacheNameFromUrl( url ) {
405
+
406
+ const API_REG_EXP = /p\/.+com\/(.*?)\//;
407
+ const matchArray = url.toString().match( API_REG_EXP );
408
+
409
+ return matchArray && matchArray.length >= 1 ? matchArray[1] : null;
410
+
411
+ }
412
+
413
+ function expiredCache( timeCached ) {
414
+
415
+ const now = new Date().getTime();
416
+
417
+ return Math.abs( now - timeCached ) >= CACHED_EXPIRY_TIMESTAMP;
418
+
419
+ }
420
+
421
+
422
+ export default CacheAPI
@@ -1,6 +1,35 @@
1
- import Fetch from '../Fetch';
2
1
 
3
2
 
3
+ export const OnOKResponse = ( fn ) => {
4
+ return ( [network, isAbort] ) => {
5
+
6
+ //Is any status is outside 200 - 299 it is not ok
7
+ if ( network.status.code < 200 || network.status.code >= 300 || isAbort ) {
8
+ return [network, isAbort];
9
+ }
10
+
11
+ //Run the function since its all ok
12
+ return fn( [network, isAbort] );
13
+ }
14
+ }
15
+
16
+
17
+ export const getCacheByName = async ( name ) => {
18
+ try {
19
+ return caches.open( name );
20
+ } catch ( err ) {
21
+ throw ( err );
22
+ }
23
+ }
24
+
25
+
26
+ export const putJsonInCache = ( cache, url, json ) => {
27
+
28
+ const response = new Response( JSON.stringify( json ), responseObjectJson );
29
+
30
+ return cache.put( url, response )
31
+
32
+ }
4
33
 
5
34
  export const createUrlParams = ( params, existingParams ) => {
6
35
 
@@ -52,7 +81,7 @@ export const createUrlParams = ( params, existingParams ) => {
52
81
  }
53
82
 
54
83
 
55
- export async function fetchPagedURL( url, callback, options ) {
84
+ export const fetchPagedURL = ( Fetch ) => async ( url, callback, options ) => {
56
85
 
57
86
  const finalOptions = {
58
87
  skipCache: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selkirk-systems/fetch",
3
- "version": "1.5.2",
3
+ "version": "1.7.0",
4
4
  "description": "Abortable fetch library",
5
5
  "keywords": [],
6
6
  "author": "Marcos Bernal <mbernal@selkirksystems.com>",
@@ -36,5 +36,5 @@
36
36
  "peerDependencies": {
37
37
  "@selkirk-systems/state-management": ">=1.0.0"
38
38
  },
39
- "gitHead": "97254eb48b612c80120c1285278c8bda7c5b8874"
39
+ "gitHead": "66fcf1754a7a7feaece908c6368ae08efbf8d63b"
40
40
  }