-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
use workers for full API routes cache busting in development mode
- Loading branch information
1 parent
9686fc1
commit e49da21
Showing
2 changed files
with
109 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// https://github.com/nodejs/modules/issues/307#issuecomment-858729422 | ||
import { parentPort } from 'worker_threads'; | ||
|
||
// based on https://stackoverflow.com/questions/57447685/how-can-i-convert-a-request-object-into-a-stringifiable-object-in-javascript | ||
async function responseAsObject (response) { | ||
if (!response instanceof Response) { | ||
throw Object.assign( | ||
new Error(), | ||
{ name: 'TypeError', message: 'Argument must be a Response object' } | ||
); | ||
} | ||
response = response.clone(); | ||
|
||
function stringifiableObject (obj) { | ||
const filtered = {}; | ||
for (const key in obj) { | ||
if (['boolean', 'number', 'string'].includes(typeof obj[key]) || obj[key] === null) { | ||
filtered[key] = obj[key]; | ||
} | ||
} | ||
return filtered; | ||
} | ||
|
||
return { | ||
...stringifiableObject(response), | ||
headers: Object.fromEntries(response.headers), | ||
// signal: stringifiableObject(request.signal), | ||
body: await response.text() | ||
}; | ||
} | ||
|
||
async function executeRouteModule({ href, request }) { | ||
// console.log('WORKER', { href, message, request }) | ||
const { handler } = await import(href); | ||
const response = await handler(request); | ||
|
||
// console.log('WORKER', { response }) | ||
parentPort.postMessage(await responseAsObject(response)); | ||
} | ||
|
||
parentPort.on('message', async (task) => { | ||
await executeRouteModule(task); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters