minor serviceWorker tweaks to url matching and 302 redirects

This commit is contained in:
Danny Coates 2018-09-05 10:35:36 -07:00
parent 7c6aabc388
commit a1fa36b79c
No known key found for this signature in database
GPG Key ID: 4C442633C62E00CB

View File

@ -41,7 +41,7 @@ async function decryptStream(id) {
type = 'application/zip'; type = 'application/zip';
size = zip.size; size = zip.size;
} }
const readStream = transformStream( const responseStream = transformStream(
zipStream || decrypted, zipStream || decrypted,
{ {
transform(chunk, controller) { transform(chunk, controller) {
@ -62,22 +62,26 @@ async function decryptStream(id) {
'Content-Type': type, 'Content-Type': type,
'Content-Length': size 'Content-Length': size
}; };
return new Response(readStream, { headers }); return new Response(responseStream, { headers });
} catch (e) { } catch (e) {
if (noSave) { if (noSave) {
return new Response(null, { status: e.message }); return new Response(null, { status: e.message });
} }
const redirectRes = await fetch(`/download/${id}`); return new Response(null, {
return new Response(redirectRes.body, { status: 302 }); status: 302,
headers: {
Location: `/download/${id}`
}
});
} }
} }
self.onfetch = event => { self.onfetch = event => {
const req = event.request; const req = event.request;
if (/\/api\/download\/[A-Fa-f0-9]{4,}/.test(req.url)) { const match = /\/api\/download\/([A-Fa-f0-9]{4,})/.exec(req.url);
const id = req.url.split('/')[5]; if (match) {
event.respondWith(decryptStream(id)); event.respondWith(decryptStream(match[1]));
} }
}; };