From d004e9681e490e2eed1a03eb6cb53dc828493e23 Mon Sep 17 00:00:00 2001
From: dm1sh <me@dmitriy.icu>
Date: Sat, 31 Jul 2021 21:58:45 +0300
Subject: [PATCH] Added /upload handler in service worker

---
 src/serviceWorker/db.ts            |  7 +++++++
 src/serviceWorker/fetchHandlers.ts | 20 ++++++++++++++++++++
 src/serviceWorker/index.ts         |  3 ++-
 3 files changed, 29 insertions(+), 1 deletion(-)

diff --git a/src/serviceWorker/db.ts b/src/serviceWorker/db.ts
index aa64808..4fb8aa5 100644
--- a/src/serviceWorker/db.ts
+++ b/src/serviceWorker/db.ts
@@ -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);
diff --git a/src/serviceWorker/fetchHandlers.ts b/src/serviceWorker/fetchHandlers.ts
index 7668de9..d29f578 100644
--- a/src/serviceWorker/fetchHandlers.ts
+++ b/src/serviceWorker/fetchHandlers.ts
@@ -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));
+  }
+};
diff --git a/src/serviceWorker/index.ts b/src/serviceWorker/index.ts
index 927a0a1..835c112 100644
--- a/src/serviceWorker/index.ts
+++ b/src/serviceWorker/index.ts
@@ -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) },
   ];