Skip to content
This repository was archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
Handle partial/range requests from service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
aabounegm committed Apr 20, 2022
1 parent a6cf6e4 commit 45f2697
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Courtesy of https://dev.to/100lvlmaster/create-a-pwa-with-sveltekit-svelte-a36
import { build, files, version } from '$service-worker';
import { handleRequestsWith } from 'worker-request-response';
import { createPartialResponse } from 'workbox-range-requests';
import type {
CheckStatusRequest,
QueryDownloadsRequest,
Expand Down Expand Up @@ -47,14 +48,19 @@ async function fetchAndCache(request: Request) {
if (isAudio) {
const cached = await cache.match(request.url);
if (cached) {
if (request.headers.has('Range')) {
return createPartialResponse(request, cached);
}
return cached;
}
}
const shouldCache = new URL(request.url).searchParams.get('download') === 'true';

try {
const response = await fetch(request);
if (!isAudio || shouldCache) {
// Don't cache partial responses
const isFull = !response.headers.has('content-range');
if ((!isAudio && isFull) || shouldCache) {
const url = new URL(request.url);
url.searchParams.delete('download');
cache.put(url.toString(), response.clone());
Expand Down

0 comments on commit 45f2697

Please sign in to comment.