From 684f82f24e7e3792086198e3270ccca0d763f56d Mon Sep 17 00:00:00 2001 From: Joxit Date: Sun, 4 Jun 2023 09:17:22 +0200 Subject: [PATCH] perf: add http cache for blobs and manifests sha256 --- src/scripts/cache-request.js | 32 ++++++++++++++++++++++++++++++++ src/scripts/http.js | 7 +++++++ 2 files changed, 39 insertions(+) create mode 100644 src/scripts/cache-request.js diff --git a/src/scripts/cache-request.js b/src/scripts/cache-request.js new file mode 100644 index 0000000..293d4f1 --- /dev/null +++ b/src/scripts/cache-request.js @@ -0,0 +1,32 @@ +const SHA_REGEX = /(blobs|manifests)\/sha256:[a-f0-9]+$/; + +const getSha256 = (method, url) => { + if (method !== 'GET') { + return; + } + const parts = SHA_REGEX.exec(url); + if (!parts || !parts[0]) { + return; + } + return parts[0]; +}; + +export const getFromCache = (method, url) => { + const sha256 = getSha256(method, url); + if (!sha256) { + return; + } + try { + return sessionStorage.getItem(sha256); + } catch (e) {} +}; + +export const setCache = (method, url, responseText) => { + const sha256 = getSha256(method, url); + if (!sha256) { + return; + } + try { + sessionStorage.setItem(sha256, responseText); + } catch (e) {} +}; diff --git a/src/scripts/http.js b/src/scripts/http.js index ca5e072..b176589 100644 --- a/src/scripts/http.js +++ b/src/scripts/http.js @@ -15,6 +15,8 @@ * along with this program. If not, see . */ +import { getFromCache, setCache } from './cache-request'; + export class Http { constructor(opts) { this.oReq = new XMLHttpRequest(); @@ -78,6 +80,7 @@ export class Http { req.send(); }); } else { + this.status === 200 && setCache(self._method, self._url, this.responseText); f.bind(this)(); } }); @@ -116,6 +119,10 @@ export class Http { } send() { + const responseText = getFromCache(this._method, this._url); + if (responseText) { + return this._events['loadend'].bind({ status: 200, responseText })(); + } this.oReq.send(); } }