@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.
package/lib/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;
@@ -17,8 +15,6 @@ const CONTENT_TYPE_DOWNLOADS = {
17
15
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true
18
16
  }
19
17
 
20
- //30 minutes
21
- const CACHED_EXPIRY_TIMESTAMP = 30 * 60000;
22
18
 
23
19
  //We store the original promise.catch so we can override it in some
24
20
  //scenarios when we want to swallow errors vs bubble them up.
@@ -44,20 +40,6 @@ export function applyMiddleware( middleware = [] ) {
44
40
  _middlewares.push( FetchErrorHandler );
45
41
  }
46
42
 
47
-
48
- export function OnOKResponse( fn ) {
49
- return ( [network, isAbort] ) => {
50
-
51
- //Is any status is outside 200 - 299 it is not ok
52
- if ( network.status.code < 200 || network.status.code >= 300 || isAbort ) {
53
- return [network, isAbort];
54
- }
55
-
56
- //Run the function since its all ok
57
- return fn( [network, isAbort] );
58
- }
59
- }
60
-
61
43
  function isServiceWorker() {
62
44
  return self;
63
45
  }
@@ -338,7 +320,7 @@ function _applyMiddleware( err, response, options ) {
338
320
  * Unwrap the response payload from the given response based on the reported
339
321
  * content-type.
340
322
  */
341
- async function unwrapResponseData( response ) {
323
+ export async function unwrapResponseData( response ) {
342
324
 
343
325
  var contentType = response.headers.has( "content-type" )
344
326
  ? response.headers.get( "content-type" )
@@ -550,438 +532,5 @@ function normalizeTransportError( transportError, request, config ) {
550
532
 
551
533
  }
552
534
 
553
- const responseObjectJson = {
554
- status: 200,
555
- headers: {
556
- 'Content-Type': 'application/json'
557
- }
558
- }
559
-
560
- export const getCacheByName = async ( name ) => {
561
- try {
562
- return caches.open( name );
563
- } catch ( err ) {
564
- throw ( err );
565
- }
566
- }
567
-
568
-
569
- export const putJsonInCache = ( cache, url, json ) => {
570
-
571
- const response = new Response( JSON.stringify( json ), responseObjectJson );
572
-
573
- return cache.put( url, response )
574
-
575
- }
576
-
577
- const _caches = {};
578
-
579
- const _updatingCache = {
580
-
581
- }
582
-
583
- const DATA_METHODS = {
584
- "GET": null,
585
- "PATCH": null,
586
- "POST": null,
587
- "PUT": null
588
- }
589
-
590
-
591
-
592
- const _fetch = ( url, options = {} ) => {
593
-
594
- const cacheName = getCacheNameFromUrl( url );
595
-
596
- //HANDLE: Service worker BS, environment is different don't cache if were in a service worker.
597
- if ( !self || !cacheName ) {
598
- return Fetch( url, options );
599
- }
600
-
601
- let _cache = _caches[cacheName];
602
-
603
- async function cacheResponse( [response, isAbort] ) {
604
-
605
- const status = response.status.code;
606
- const headers = response.request.headers;
607
- const method = response.request.method;
608
-
609
-
610
- if ( status >= 200 && status < 400 && headers.get( 'content-type' ) === "application/json" ) {
611
-
612
- if ( DATA_METHODS.hasOwnProperty( method ) ) {
613
-
614
- const data = serializeData( response.data );
615
-
616
- //HANDLE: List/Array like responses
617
- if ( data.page && !data.items || data.items && data.items.length === 0 ) {
618
-
619
- deleteFromCache( _cache, url, response );
620
-
621
- return [response, isAbort];
622
-
623
- }
624
-
625
- //HANDLE: Record like response
626
- if ( data.id ) {
627
-
628
- let uuid = getUUID( url.toString() );
629
- let matchOptions = {};
630
-
631
- if ( method === "POST" ) {
632
-
633
- uuid = {
634
- id: data.id,
635
- shortPath: url.toString()
636
- }
637
-
638
- }
639
-
640
- /**
641
- * 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
642
- * 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
643
- * and the records should all show up in UI at the top. This is the most common UX for adding records to a list,
644
- * one day some how figure out a less fragile robust method.
645
- *
646
- * Perhaps we should just refetch all the matched cache urls... but this could be huge and slow and network heavy...
647
- */
648
- await cacheFindAllLike( { cache: _cache, url: uuid.shortPath, property: "id", value: data.id, method: method } )
649
- .then( async ( matches ) => {
650
-
651
- if ( matches.length ) {
652
-
653
- const finalOptions = { ...responseObjectJson };
654
- finalOptions.headers['Time-Cached'] = new Date().getTime();
655
-
656
- await matches.forEach( async match => {
657
-
658
- const items = extractDataArray( match.data );
659
-
660
- //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
661
- // else based on sort etc.
662
- if ( method === "POST" ) {
663
- items.unshift( data );
664
- }
665
- else {
666
- items[match.matchIndex] = data;
667
- }
668
-
669
- const responseObj = new Response( JSON.stringify( match.data ), finalOptions );
670
-
671
- dispatch( UPDATE_CACHE, { url: new URL( match.request.url ), response: match.response } );
672
-
673
- return _cache.put( match.request.url, responseObj );
674
-
675
- } )
676
-
677
- }
678
- } )
679
-
680
- return [response, isAbort];
681
-
682
- }
683
-
684
- const finalOptions = { ...responseObjectJson };
685
- finalOptions.headers['Time-Cached'] = new Date().getTime();
686
-
687
- const responseObj = new Response( JSON.stringify( response.data ), finalOptions );
688
- _cache.put( url, responseObj );
689
-
690
- dispatch( UPDATE_CACHE, { url: url, response: response } );
691
-
692
- return [response, isAbort];
693
- }
694
-
695
- if ( method === "DELETE" ) {
696
-
697
- deleteFromCache( _cache, url, response );
698
- return [response, isAbort];
699
-
700
- }
701
-
702
-
703
- }
704
-
705
- return [response, isAbort];
706
-
707
- }
708
-
709
- function cacheMatch() {
710
-
711
- //HANDLE: Data updates, always return fresh data
712
- if ( options.skipCache || options.method && DATA_METHODS.hasOwnProperty( options.method ) ) {
713
-
714
- return Fetch( url, options ).then( cacheResponse );
715
-
716
- }
717
-
718
- const uuid = getUUID( url.toString() );
719
-
720
- //HANDLE: individual records, if we are looking for a record check cache for any array or search results with this record
721
- if ( uuid.id ) {
722
-
723
- return cacheFindLike( { cache: _cache, url: uuid.shortPath, property: "id", value: uuid.id } ).then( ( match ) => {
724
-
725
- if ( match ) {
726
-
727
- //Behind the scenes still fetch the record and update the cache but don't make the user wait for it.
728
- Fetch( url, options ).then( cacheResponse );
729
-
730
- const responseObj = new Response( JSON.stringify( match.match ) );
731
-
732
- return Promise.resolve( [{
733
- request: null,
734
- response: responseObj,
735
- data: match.match,
736
- status: {
737
- code: 200,
738
- text: '',
739
- isAbort: false
740
- },
741
- }, false] )
742
- }
743
-
744
-
745
- return Fetch( url, options ).then( cacheResponse );
746
-
747
- } )
748
-
749
- }
750
-
751
-
752
- return _cache.match( url ).then( ( response ) => {
753
-
754
- if ( response ) {
755
-
756
- const timeCached = response.headers.get( 'Time-Cached' );
757
-
758
- if ( expiredCache( timeCached ) ) {
759
-
760
- _cache.delete( url );
761
- return Fetch( url, options ).then( cacheResponse );
762
-
763
- }
764
-
765
- return unwrapResponseData( response ).then( ( obj ) => {
766
- Fetch( url, options ).then( cacheResponse )
767
- return Promise.resolve( [{
768
- request: null,
769
- response: response,
770
- data: obj,
771
- status: {
772
- code: response.status,
773
- text: response.statusText,
774
- isAbort: false
775
- },
776
- }, false] )
777
- } )
778
-
779
-
780
- }
781
-
782
- return Fetch( url, options ).then( cacheResponse );
783
- } )
784
- }
785
-
786
-
787
-
788
- if ( _cache ) {
789
- return cacheMatch()
790
- }
791
-
792
-
793
- return caches.open( cacheName ).then( ( cache ) => {
794
- _caches[cacheName] = cache;
795
- _cache = cache;
796
- } ).then( cacheMatch )
797
-
798
- }
799
-
800
-
801
- function deleteFromCache( _cache, url, response ) {
802
-
803
- _cache.delete( url );
804
- dispatch( DELETE_FROM_CACHE, { url: url, response: response } );
805
-
806
- }
807
-
808
- function cacheFindAllLike( options ) {
809
-
810
- const finalOptions = {
811
- ...options,
812
- findAll: true
813
- }
814
-
815
- return cacheFindLike( finalOptions );
816
- }
817
-
818
- function cacheFindLike( options ) {
819
-
820
- const cache = options.cache;
821
- const url = options.url;
822
- const property = options.property;
823
- const value = options.value;
824
- const findAll = options.findAll;
825
- const matchOptions = options.matchOptions
826
- const method = options.method || "GET";
827
-
828
- return cache.keys().then( ( keys ) => {
829
-
830
- const matchingRequests = [];
831
-
832
- for ( let i = 0; i < keys.length; i++ ) {
833
-
834
- const request = keys[i];
835
-
836
- if ( looksLikeResultListUrl( request.url, url ) ) {
837
-
838
- matchingRequests.push( cache.match( request, matchOptions ).then( ( match ) => {
839
-
840
- match._request = request;
841
-
842
- return match;
843
- } ) )
844
-
845
- }
846
-
847
- }
848
-
849
- return Promise.all( matchingRequests ).then( ( responses ) => {
850
- let count = 0;
851
-
852
- const ret = [];
853
-
854
- const checkCache = async ( index ) => {
855
-
856
- if ( index >= responses.length ) return ret;
857
-
858
- return serializeResponse( responses[index] ).then( json => {
859
-
860
- const items = extractDataArray( json );
861
- const response = responses[count];
862
-
863
- const retObj = {
864
- request: response._request,
865
- response: response,
866
- data: json,
867
- match: json,
868
- matchIndex: -1,
869
- status: {
870
- code: response.status,
871
- text: response.statusText,
872
- isAbort: false
873
- }
874
- }
875
-
876
- if ( method === "POST" ) {
877
- return findAll ? [retObj] : retObj;
878
- }
879
-
880
- const matchIndex = items.findIndex( item => item[property] === value );
881
-
882
- count++;
883
-
884
- if ( matchIndex >= 0 ) {
885
-
886
- retObj.match = items[matchIndex];
887
- retObj.matchIndex = matchIndex;
888
-
889
- if ( !findAll ) {
890
- return retObj;
891
- }
892
- else {
893
- ret.push( retObj );
894
- }
895
-
896
- return checkCache( count );
897
- }
898
-
899
-
900
- if ( count >= responses.length ) {
901
- return findAll ? ret : null;
902
- }
903
-
904
- return checkCache( count );
905
-
906
- } )
907
- }
908
-
909
- if ( !responses || !responses.length ) return findAll ? ret : null;
910
-
911
- return checkCache( count );
912
- } )
913
- } );
914
-
915
-
916
- }
917
-
918
- /**
919
- * Check if request.url looks like a list result type url, if it contains a UUID it is likely not.
920
- * @param {*} requestURL
921
- * @param {*} matchURL
922
- * @returns
923
- */
924
- function looksLikeResultListUrl( requestURL, matchURL ) {
925
-
926
- const uuid = getUUID( requestURL.toString() );
927
-
928
- return !uuid.id && requestURL.indexOf( matchURL ) >= 0;
929
- }
930
-
931
-
932
- function extractDataArray( obj ) {
933
- for ( var prop in obj._embedded ) {
934
- if ( !obj._embedded.hasOwnProperty( prop ) ) continue;
935
- return obj._embedded[prop];
936
- }
937
-
938
- return [obj];
939
- }
940
-
941
- async function serializeResponse( response ) {
942
-
943
- return response.text().then( data => {
944
- return JSON.parse( data );
945
- } )
946
-
947
- }
948
-
949
- function getUUID( str ) {
950
-
951
- const UUID_REG_EXP = /.+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}).*?/;
952
- const match = UUID_REG_EXP.exec( str );
953
-
954
- let id, shortPath;
955
-
956
- if ( match && match[1] ) {
957
- id = match[1];
958
- shortPath = str.split( `/${id}` )[0];
959
- }
960
-
961
- return {
962
- id: id,
963
- shortPath: shortPath
964
- }
965
-
966
- }
967
-
968
-
969
-
970
- function getCacheNameFromUrl( url ) {
971
-
972
- const API_REG_EXP = /p\/.+com\/(.*?)\//;
973
- const matchArray = url.toString().match( API_REG_EXP );
974
-
975
- return matchArray && matchArray.length >= 1 ? matchArray[1] : null;
976
-
977
- }
978
-
979
- function expiredCache( timeCached ) {
980
-
981
- const now = new Date().getTime();
982
-
983
- return Math.abs( now - timeCached ) >= CACHED_EXPIRY_TIMESTAMP;
984
-
985
- }
986
535
 
987
- export default _fetch;
536
+ export default Fetch;
package/lib/index.js CHANGED
@@ -1,5 +1,6 @@
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
 
4
5
  export * from "./utils/FetchUtils";
5
6
  export * from "./constants/FetchConstants";