Przeglądaj źródła

demo pwa: added deleting old caches

mattias 3 lat temu
rodzic
commit
82545c3ee6
2 zmienionych plików z 29 dodań i 3 usunięć
  1. 5 0
      demo/pwa/ServiceWorker.lpi
  2. 24 3
      demo/pwa/ServiceWorker.lpr

+ 5 - 0
demo/pwa/ServiceWorker.lpi

@@ -29,6 +29,11 @@
     <RunParams>
       <FormatVersion Value="2"/>
     </RunParams>
+    <RequiredPackages>
+      <Item>
+        <PackageName Value="pas2js_rtl"/>
+      </Item>
+    </RequiredPackages>
     <Units>
       <Unit>
         <Filename Value="ServiceWorker.lpr"/>

+ 24 - 3
demo/pwa/ServiceWorker.lpr

@@ -3,10 +3,10 @@ program ServiceWorker;
 {$mode objfpc}
 
 uses
-  JS, Web;
+  JS, Web, Types;
 
 const
-  CacheName = 'v4';
+  CacheName = 'v5';
 
   FallbackURL = '/images/error.png';
 
@@ -88,10 +88,31 @@ begin
     await(serviceWorker.registration.navigationPreload.enable());
 end;
 
+procedure DeleteCache(key: string); async;
 begin
-  serviceWorker.addEventListener('activate', procedure(Event: TJSExtendableEvent)
+  await(boolean,caches.delete(key));
+end;
+
+function DeleteOldCaches: jsvalue; async;
+var
+  CacheKeepList: TStringDynArray;
+  CachesToDelete, KeyList: TJSArray;
+begin
+  CacheKeepList := [CacheName];
+  KeyList := await(TJSArray,caches.keys());
+  CachesToDelete := keyList.filter(
+    function (key: JSValue; index: NativeInt; anArray : TJSArray) : Boolean
+    begin
+      Result:=not TJSArray(CacheKeepList).includes(key);
+    end);
+  Result:=await(jsvalue,TJSPromise.all(CachesToDelete.map(TJSArrayMapEvent(@DeleteCache))));
+end;
+
+begin
+  ServiceWorker.addEventListener('activate', procedure(Event: TJSExtendableEvent)
     begin
       Event.waitUntil(EnableNavigationPreload());
+      event.waitUntil(DeleteOldCaches());
     end);
 
   ServiceWorker.addEventListener('install', procedure(Event: TJSExtendableEvent)