Event handlers must respond before dispatching another event

This commit is contained in:
byte[] 2021-10-28 21:06:37 -04:00
parent 9c51433550
commit 53e026f8f3
2 changed files with 10 additions and 10 deletions

View file

@ -15,15 +15,15 @@ export function handleDownload(event: FetchEvent, url: URL): void {
return event.respondWith(new Response('Don\'t know what to download!', { status: 400 }));
}
const generateResponse = ifOk((upstream: Response) => {
const headers = new Headers(upstream.headers);
const response =
fetch(target)
.then(ifOk((upstream: Response) => {
const headers = new Headers(upstream.headers);
headers.set('content-disposition', `attachment; filename="${escapeFilename(name)}"`);
headers.set('content-disposition', `attachment; filename="${escapeFilename(name)}"`);
return new Response(upstream.body, { headers });
});
return new Response(upstream.body, { headers });
}));
fetch(target)
.then(generateResponse)
.then(event.respondWith);
event.respondWith(response);
}

View file

@ -70,7 +70,7 @@ function fetchBackoff(...fetchArgs) {
*/
function escapeFilename(name) {
return name
.replace(/[^-_+a-zA-Z0-9]/, '_')
.replace(/[^.-_+a-zA-Z0-9]/, '_')
.substring(0, 150);
}
@ -82,7 +82,7 @@ function escapeFilename(name) {
*/
function ifOk(responseGenerator) {
return resp => {
if (resp.ok) return new Response(responseGenerator(resp));
if (resp.ok) return responseGenerator(resp);
return resp;
};
}