Started react app integration with service worker. Uploading book to server now also saves result to indexedDB

This commit is contained in:
Dmitriy Shishkov 2021-08-01 13:47:52 +03:00
parent aa98de6bd5
commit b6ede385ca
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
4 changed files with 23 additions and 17 deletions

View File

@ -1,5 +1,5 @@
export const API_URL = process.env.PUBLIC_API_URL;
// export const BASE_URL = process.env.PUBLIC_BASE_URL;
export const CACHE = "v1";
export const API_URL = process.env.PUBLIC_API_URL || "";
export const BASE_URL = process.env.PUBLIC_BASE_URL || "";
export const CACHE = "v1.0.1";
export const DB_NAME = "publite";
export const DB_VERSION = 1;
export const DB_VERSION = 101;

View File

@ -2,7 +2,7 @@ export const register = () => {
if ("serviceWorker" in navigator) {
window.addEventListener("load", () =>
navigator.serviceWorker
.register("/sw.js")
.register("/sw.js", { scope: "" })
.then((registration) => {
if (process.env.NODE_ENV === "development")
console.log(

View File

@ -28,7 +28,7 @@ export const handleBookUpload = async (request: Request) => {
if (res.ok) {
const book = await res.json();
await saveBook(book);
return new Response(book);
return new Response(JSON.stringify(book));
} else throw new Error(res.status.toString() + res.statusText);
} catch (err) {
return new Response(JSON.stringify(err));

View File

@ -1,3 +1,4 @@
import { API_URL } from "~/constants";
import { fromCache, precache } from "./cache";
import { openDB as createDB } from "./db";
import {
@ -11,23 +12,28 @@ import { getHash } from "./utils";
declare const self: ServiceWorkerGlobalScope;
self.addEventListener("install", (event) => {
self.skipWaiting();
event.waitUntil(precache());
});
self.addEventListener("install", (event) => event.waitUntil(precache()));
self.addEventListener("activate", (event) => event.waitUntil(createDB()));
self.addEventListener("activate", (event) => {
self.clients.claim();
event.waitUntil(createDB());
});
self.addEventListener("fetch", (event) => {
const { request } = event;
const path = new URL(request.url).pathname;
const handlers: PathHandler[] = [
{ path: "/list", getResponse: () => handleBooks() },
{ path: "/book/", getResponse: () => handleBook(request, getHash(path)) },
{ path: "/upload", getResponse: () => handleBookUpload(request) },
{ path: "", getResponse: () => fromCache(request) },
];
let handlers: PathHandler[];
if (request.url.startsWith(API_URL)) {
handlers = [
{ path: "/list", getResponse: () => handleBooks() },
{ path: "/book/", getResponse: () => handleBook(request, getHash(path)) },
{ path: "/uploadfile", getResponse: () => handleBookUpload(request) },
];
} else {
handlers = [{ path: "", getResponse: () => fromCache(request) }];
}
event.respondWith(handle(path, handlers));
});