Skip to content

Commit

Permalink
added background sync for POST requests
Browse files Browse the repository at this point in the history
  • Loading branch information
WhyAsh5114 committed Dec 27, 2023
1 parent 56e1927 commit 74a215a
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,17 @@ import {
cleanupOutdatedCaches
} from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { NetworkFirst, CacheFirst } from "workbox-strategies";
import { NetworkFirst, CacheFirst, NetworkOnly } from "workbox-strategies";
import { BackgroundSyncPlugin } from "workbox-background-sync";
declare let self: ServiceWorkerGlobalScope;

const cacheFirstDestinations: RequestDestination[] = ["style", "manifest", "image"];
const strategyOptions = {
plugins: [
new PrecacheFallbackPlugin({
fallbackURL: "/offline"
})
]
};
const fallbackPlugin = new PrecacheFallbackPlugin({ fallbackURL: "/offline" });
const backgroundSyncPlugin = new BackgroundSyncPlugin("pendingRequests");

function routingStrategyFunction(mode: "networkFirst" | "cacheFirst", request: Request, url: URL) {
// Ignore POST API endpoints (should be network only)
if (url.pathname.startsWith("/api") && request.method === "POST") return false;
// Ignore /auth requests
if (url.pathname.startsWith("/auth")) return false;
// Decide whether or not asset should be cached (cacheFirstDestinations, and unplugin-icons)
Expand All @@ -31,20 +29,29 @@ function routingStrategyFunction(mode: "networkFirst" | "cacheFirst", request: R
}

cleanupOutdatedCaches();
precacheAndRoute(self.__WB_MANIFEST);
precacheAndRoute(self.__WB_MANIFEST, { ignoreURLParametersMatching: [/callbackURL/] });

self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") self.skipWaiting();
});

// Network first for everything except static assets
registerRoute(
({ url }) => url.pathname.startsWith("/api"),
new NetworkOnly({
plugins: [backgroundSyncPlugin],
networkTimeoutSeconds: 5
}),
"POST"
);

// Network first for everything except static assets, /auth, and /api
registerRoute(
({ request, url }) => routingStrategyFunction("networkFirst", request, url),
new NetworkFirst(strategyOptions)
new NetworkFirst({ plugins: [fallbackPlugin], networkTimeoutSeconds: 5 })
);

// Cache first for images, css
registerRoute(
({ request, url }) => routingStrategyFunction("cacheFirst", request, url),
new CacheFirst(strategyOptions)
new CacheFirst({ plugins: [fallbackPlugin] })
);

0 comments on commit 74a215a

Please sign in to comment.