Added fetch handler in service worker

This commit is contained in:
Dmitriy Shishkov 2021-07-31 21:55:05 +03:00
parent 12ce54e95d
commit 1b7fa0bacf
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
3 changed files with 33 additions and 4 deletions

View File

@ -11,12 +11,13 @@ export const precache = async () =>
/**
* Requests file from network or gets it from cache if offline
*/
export const fromCache = async (request: Request) => {
export const fromCache = async (request: Request): Promise<Response> => {
try {
const response = await fetch(request);
(await getCache()).put(request, response);
(await getCache()).put(request, response.clone());
return response;
} catch (err) {
return (await getCache()).match(request);
const response = await (await getCache()).match(request);
return response || new Response();
}
};

View File

@ -0,0 +1,16 @@
export interface PathHandler {
/** Path start for handler */
path: string;
/** Function returning Response object */
getResponse: () => Response | Promise<Response>;
}
/**
* Routes fetch request path to specified handler
*/
export const handle = (requestPath: string, table: PathHandler[]) => {
for (const { path, getResponse: response } of table)
if (requestPath.startsWith(path)) return response();
return new Response();
};

View File

@ -1,5 +1,6 @@
import { precache } from "./cache";
import { fromCache, precache } from "./cache";
import { openDB as createDB } from "./db";
import { handle, PathHandler } from "./fetchHandlers";
declare const self: ServiceWorkerGlobalScope;
@ -9,3 +10,14 @@ self.addEventListener("install", (event) => {
});
self.addEventListener("activate", (event) => event.waitUntil(createDB()));
self.addEventListener("fetch", (event) => {
const { request } = event;
const path = new URL(request.url).pathname;
const handlers: PathHandler[] = [
{ path: "", getResponse: () => fromCache(request) },
];
event.respondWith(handle(path, handlers));
});