Skip to content

Commit

Permalink
feat: add cache image
Browse files Browse the repository at this point in the history
  • Loading branch information
dewanakl committed Jan 20, 2025
1 parent 010dcd3 commit 101ea75
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ <h2 class="font-esthetic mb-4" style="font-size: 2.5rem;">Wahyu &amp; Riski</h2>
<div class="progress" role="progressbar" style="height: 0.5rem;">
<div class="progress-bar" id="progress-bar" style="width: 0%"></div>
</div>
<small class="mt-1 text-light" id="progress-info" style="display: none;">Loading</small>
<small class="mt-1 text-light" id="progress-info" style="display: none;">Booting Application...</small>
<noscript>
<small class="mt-1 text-danger">Sorry, this invitation requires javascript to work</small>
</noscript>
Expand Down
36 changes: 32 additions & 4 deletions js/app/guest/guest.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,41 @@ export const guest = (() => {
* @returns {void}
*/
const getByFetch = (el) => {
fetch(el.getAttribute('data-src'))
.then((res) => res.blob())
.then((b) => {
// 6 hour TTL
const ttl = 1000 * 60 * 60 * 6;
const url = el.getAttribute('data-src');
const exp = 'x-expiration-time';
const cacheName = 'image_cache';

/**
* @param {Cache} cache
* @returns {Promise<blob>}
*/
const fetchPut = (cache) => {
return fetch(url).then((res) => res.blob().then((b) => {
const headers = new Headers(res.headers);
headers.append(exp, String(Date.now() + ttl));

return cache.put(url, new Response(b, { headers })).then(() => b);
}));
};

caches.open(cacheName).then((cache) => {
cache.match(url).then((res) => {
if (!res) {
return fetchPut(cache);
}

if (Date.now() <= parseInt(res.headers.get(exp), 10)) {
return res.blob();
}

return cache.delete(url).then((s) => s ? fetchPut(cache) : res.blob());
}).then((b) => {
el.src = URL.createObjectURL(b);
progress.complete('image');
})
.catch(() => progress.invalid('image'));
}).catch(() => progress.invalid('image'));
};

/**
Expand Down

0 comments on commit 101ea75

Please sign in to comment.