Added /upload handler in service worker
This commit is contained in:
parent
1b7fa0bacf
commit
d004e9681e
@ -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);
|
||||
|
@ -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));
|
||||
}
|
||||
};
|
||||
|
@ -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) },
|
||||
];
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user