feat(web-reader): HTTP Caching & Cache Storage for content responses (#75)
* Squashed commit of the following: commit e799d02a1b3557fcbe9c67bd276ced9ddc783e83 Author: Nam Le <namle888029@gmail.com> Date: Wed Apr 1 18:47:08 2026 +0700 should be done commit d232c4d48bd97dbc7d8d800cdb3d18e85a73b8ec Author: Nam Le <namle888029@gmail.com> Date: Wed Apr 1 18:32:49 2026 +0700 ok done commit 911d69c3347c6596ae0feb3261355f7b234b6171 Author: Nam Le <namle888029@gmail.com> Date: Wed Apr 1 18:32:15 2026 +0700 dont break pls commit 498e996bb42a74f9edda65b914a9124b15a8baea Author: Nam Le <namle888029@gmail.com> Date: Sat Mar 21 11:35:32 2026 +0700 changes: + avoid double caching + detach get & validate logic + error handling for cache insert commit a215d11d6855a3381e4f2ecbca32d45d4b06869f Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 22:01:37 2026 +0700 fix dup commit 539b70f6f9c859bdf6d2a2557e3ba1c1fc10a601 Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 21:46:43 2026 +0700 fix + leaking Blob resource + scss lint + extra `}` commit d1c8ceea944c0a25a9a2a54bb83122e0a9480b05 Author: NamLe029 <146613205+NamLe029@users.noreply.github.com> Date: Fri Mar 20 21:34:14 2026 +0700 Apply suggestions from code review Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> commit ca14572c8c6df143295ebff2acf210f3a5164ed5 Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 20:25:46 2026 +0700 wording commit 558b0f69fe6a6736aa114f592abd87451b173ccb Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 19:51:28 2026 +0700 remove dexie commit 4b0750824685e70dd5a13fd9e899064fd6b009c6 Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 19:22:43 2026 +0700 use observable for pdf bookdata commit 1c88aff7c01a51a5263aca3522797624ed794862 Author: Nam Le <namle888029@gmail.com> Date: Wed Apr 1 18:07:14 2026 +0700 switch to cache storage commit c766428c32b97fab339b3438b6c4e693082a07a3 Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 15:13:42 2026 +0700 error handling commit bdbaa8f5f769fcd80f3f93aac0c52ffba8bcec27 Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 14:16:49 2026 +0700 cleanup unecessary validation commit 56e264ee5570948cf1512c8ce4de4622430d3cdc Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 12:50:45 2026 +0700 apply simpleCacheService commit 45ef6ae5d460b27d134b696951fd613eefcb2d64 Author: Nam Le <namle888029@gmail.com> Date: Wed Apr 1 18:02:44 2026 +0700 interface for local settings commit 421305dbcb108647b5f0cc29c567de5daee2a93d Author: Nam Le <namle888029@gmail.com> Date: Wed Apr 1 18:01:20 2026 +0700 simple cache service for caching request response commit 1aa81b4a08b006d52e398da61464527fd90e51cb Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 12:47:54 2026 +0700 local settings service for device-scoped settings commit 647b4f561336617651f5c4f14fe83dc70df3f30f Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 12:46:35 2026 +0700 add dexie dependency commit d8bfed64b0096c2d99052fceee718413b5dc8b40 Author: Nam Le <namle888029@gmail.com> Date: Fri Mar 20 12:46:00 2026 +0700 enable HTTP Caching (Last-Modified) for PDF, EPUB, audiobook content response * delete unused * final touch * move local settings * test * remove test case for deleted method * lint --------- Co-authored-by: brios <127139797+balazs-szucs@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
import {inject, Injectable} from "@angular/core";
|
||||
import {HttpClient, HttpErrorResponse, HttpResponse} from "@angular/common/http";
|
||||
import {firstValueFrom} from "rxjs";
|
||||
|
||||
@Injectable({
|
||||
providedIn: "root",
|
||||
})
|
||||
export class CacheStorageService {
|
||||
private static readonly CACHE_NAME = "storage";
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
async getCache(uri: string, noValidate: boolean = false): Promise<Response> {
|
||||
const cachedResponse = await this.attemptToGetAndValidateCache(uri, noValidate);
|
||||
if (cachedResponse) {
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
// Cache stale or failed to get, fetch from uri
|
||||
|
||||
const httpResponse = await this.fetchFromUri(uri);
|
||||
const headers = new Headers();
|
||||
httpResponse.headers.keys().forEach((key) => {
|
||||
headers.set(key, httpResponse.headers.get(key)!);
|
||||
});
|
||||
|
||||
const res = new Response(httpResponse.body, {
|
||||
headers: headers,
|
||||
status: httpResponse.status,
|
||||
statusText: httpResponse.statusText,
|
||||
});
|
||||
|
||||
this.put(uri, res.clone()).catch((error) => {
|
||||
console.error("Error caching response:", error);
|
||||
});
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws no throws
|
||||
* @returns cached response, or null if cache is stale or failed to access/validate
|
||||
*/
|
||||
private async attemptToGetAndValidateCache(uri: string, noValidate: boolean = false): Promise<Response | null> {
|
||||
let stale: boolean = true;
|
||||
let entry;
|
||||
try {
|
||||
entry = await this.match(uri);
|
||||
if (entry) {
|
||||
stale = false;
|
||||
if (!noValidate) {
|
||||
stale = !(await this.validateCacheFromUri(uri, entry));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error accessing or validating cache:", error);
|
||||
stale = true;
|
||||
}
|
||||
|
||||
if (!stale && entry)
|
||||
return entry;
|
||||
return null;
|
||||
}
|
||||
|
||||
private async fetchFromUri(uri: string): Promise<HttpResponse<ArrayBuffer>> {
|
||||
return firstValueFrom(
|
||||
this.http.get<ArrayBuffer>(uri, {
|
||||
responseType: "arraybuffer" as "json",
|
||||
observe: "response",
|
||||
cache: "no-store", // Avoid double caching
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async validateCacheFromUri(uri: string, entry: Response): Promise<boolean> {
|
||||
const h = entry.headers.get("last-modified");
|
||||
if (h == null) return false;
|
||||
try {
|
||||
const response = await firstValueFrom(
|
||||
this.http.head<ArrayBuffer>(uri, {
|
||||
observe: "response",
|
||||
responseType: "arraybuffer" as "json",
|
||||
headers: { "if-modified-since": h },
|
||||
}),
|
||||
);
|
||||
|
||||
return response.status === 304;
|
||||
} catch (error: unknown) { // It throws if the status is not 2xx
|
||||
if (error instanceof HttpErrorResponse && error.status === 304) {
|
||||
return true; // Not modified, cache is valid
|
||||
}
|
||||
console.error("Error validating cache:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
match(uri: string): Promise<Response | undefined> {
|
||||
return this.cache().then((cache) => cache.match(uri));
|
||||
}
|
||||
|
||||
has(uri: string): Promise<boolean> {
|
||||
return this.cache().then((cache) =>
|
||||
cache.match(uri).then((response) => !!response),
|
||||
);
|
||||
}
|
||||
|
||||
put(uri: string, entry: Response): Promise<void> {
|
||||
return this.cache().then((cache) => cache.put(uri, entry));
|
||||
}
|
||||
|
||||
delete(uri: string): Promise<boolean> {
|
||||
return this.cache().then((cache) => cache.delete(uri));
|
||||
}
|
||||
|
||||
clear(): Promise<void> {
|
||||
return this.cache()
|
||||
.then((cache) => cache.keys())
|
||||
.then((keys) => Promise.all(keys.map((key) => this.delete(key.url))))
|
||||
.then(() => undefined);
|
||||
}
|
||||
|
||||
getCacheSizeInBytes(): Promise<number> {
|
||||
return this.cache()
|
||||
.then((cache) => cache.keys())
|
||||
.then((keys) => keys.map((key) => this.match(key.url)))
|
||||
.then((promises) => Promise.all(promises))
|
||||
.then((responses) => responses.map(response => parseInt(response?.headers.get("content-length") || "0")))
|
||||
.then((sizes) => sizes.reduce((total, size) => total + size, 0));
|
||||
}
|
||||
|
||||
|
||||
private cache(): Promise<Cache> {
|
||||
return caches.open(CacheStorageService.CACHE_NAME);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user