Added /upload handler in service worker

This commit is contained in:
Dmitriy Shishkov 2021-07-31 21:58:45 +03:00
parent 1b7fa0bacf
commit d004e9681e
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
3 changed files with 29 additions and 1 deletions

View File

@ -1,4 +1,5 @@
import * as idb from "idb";
import { BookT } from "~/types/book";
import { DB_NAME, DB_VERSION } from "../constants";
import { PubliteDB } from "./schema";
@ -11,3 +12,9 @@ export const openDB = () =>
if (oldVersion < 1) db.createObjectStore("Books", { keyPath: "hash" });
},
});
/**
* Saves IBook object in IndexedDB
*/
export const saveBook = async (book: BookT) =>
(await openDB()).add("Books", book);

View File

@ -1,3 +1,5 @@
import { saveBook } from "./db";
export interface PathHandler {
/** Path start for handler */
path: string;
@ -14,3 +16,21 @@ export const handle = (requestPath: string, table: PathHandler[]) => {
return new Response();
};
/**
* Converts book to html with publiteBackend server.
*
* First fetch handler with network request
*/
export const handleBookUpload = async (request: Request) => {
try {
const res = await fetch(request);
if (res.ok) {
const book = await res.json();
await saveBook(book);
return new Response(book);
} else throw new Error(res.status.toString() + res.statusText);
} catch (err) {
return new Response(JSON.stringify(err));
}
};

View File

@ -1,6 +1,6 @@
import { fromCache, precache } from "./cache";
import { openDB as createDB } from "./db";
import { handle, PathHandler } from "./fetchHandlers";
import { handle, handleBookUpload, PathHandler } from "./fetchHandlers";
declare const self: ServiceWorkerGlobalScope;
@ -16,6 +16,7 @@ self.addEventListener("fetch", (event) => {
const path = new URL(request.url).pathname;
const handlers: PathHandler[] = [
{ path: "/upload", getResponse: () => handleBookUpload(request) },
{ path: "", getResponse: () => fromCache(request) },
];