Added book getting by hash in service worker

This commit is contained in:
Dmitriy Shishkov 2021-07-31 22:02:56 +03:00
parent 487b6b91bd
commit aa98de6bd5
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
4 changed files with 30 additions and 2 deletions

View File

@ -23,3 +23,9 @@ export const saveBook = async (book: BookT) =>
* Returns all books saved in IndexedDB
*/
export const getBooks = async () => (await openDB()).getAll("Books");
/**
* Gets book from IndexedDB by hash
*/
export const getBook = async (hash: string) =>
(await openDB()).get("Books", hash);

View File

@ -1,4 +1,4 @@
import { getBooks, saveBook } from "./db";
import { getBook, getBooks, saveBook } from "./db";
export interface PathHandler {
/** Path start for handler */
@ -43,3 +43,13 @@ export const handleBooks = async () => {
return new Response(JSON.stringify(list));
};
/**
* Gets book from database
*/
export const handleBook = async (request: Request, hash: string) => {
const book = await getBook(hash);
if (book) return new Response(JSON.stringify(book));
return new Response("No such book :(");
};

View File

@ -2,10 +2,12 @@ import { fromCache, precache } from "./cache";
import { openDB as createDB } from "./db";
import {
handle,
handleBook,
handleBooks,
handleBookUpload,
PathHandler,
} from "./fetchHandlers";
import { getHash } from "./utils";
declare const self: ServiceWorkerGlobalScope;
@ -21,8 +23,9 @@ self.addEventListener("fetch", (event) => {
const path = new URL(request.url).pathname;
const handlers: PathHandler[] = [
{ path: "/upload", getResponse: () => handleBookUpload(request) },
{ path: "/list", getResponse: () => handleBooks() },
{ path: "/book/", getResponse: () => handleBook(request, getHash(path)) },
{ path: "/upload", getResponse: () => handleBookUpload(request) },
{ path: "", getResponse: () => fromCache(request) },
];

View File

@ -0,0 +1,9 @@
/**
* Gets hash string from book path
*/
export const getHash = (path: string) => {
let hashLength = path.length - "/book/".length;
if (path.endsWith("/")) hashLength--;
return path.substr("/book/".length, hashLength);
};