Skip to content

Commit

Permalink
fix(service-worker): support range (#844)
Browse files Browse the repository at this point in the history
* fix(service-worker): support range

* refactor
  • Loading branch information
hyrious committed Aug 6, 2021
1 parent fb22d5f commit cae51ff
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions web/flat-web/public/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,37 @@ self.onfetch = event => {
event.respondWith(
pptConvertCache.then(async cache => {
const response = await cache.match(request);

// https://web.dev/sw-range-requests
const range = request.headers.get("range");
if (range && response) {
if (response.status === 206) {
return response;
}
try {
const blob = await response.blob();
const [x, y] = range.replace("bytes=", "").split("-");
const end = parseInt(y, 10) || blob.size - 1;
const start = parseInt(x, 10) || 0;
const sliced = blob.slice(start, end);
const slicedSize = sliced.size;
const slicedResponse = new Response(sliced, {
status: 206,
statusText: "Partial Content",
headers: response.headers,
});
slicedResponse.headers.set("Content-Length", String(slicedSize));
slicedResponse.headers.set(
"Content-Range",
`bytes ${start}-${end}/${blob.size}`,
);
return slicedResponse;
} catch (error) {
console.error(error);
return fetch(request);
}
}

return response || fetch(request);
}),
);
Expand Down

0 comments on commit cae51ff

Please sign in to comment.