mirror of
https://github.com/aljazceru/ditto.git
synced 2026-01-24 15:54:23 +01:00
Add fetchWorker for fetching off the main thread
This commit is contained in:
14
src/workers/fetch.test.ts
Normal file
14
src/workers/fetch.test.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { assert } from '@/deps-test.ts';
|
||||
|
||||
import { fetchWorker } from './fetch.ts';
|
||||
|
||||
Deno.test('fetchWorker', async () => {
|
||||
await sleep(2000);
|
||||
const response = await fetchWorker('https://example.com');
|
||||
const text = await response.text();
|
||||
assert(text.includes('Example Domain'));
|
||||
});
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
19
src/workers/fetch.ts
Normal file
19
src/workers/fetch.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Comlink } from '@/deps.ts';
|
||||
|
||||
import type { FetchWorker } from './fetch.worker.ts';
|
||||
|
||||
const _worker = Comlink.wrap<typeof FetchWorker>(
|
||||
new Worker(
|
||||
new URL('./fetch.worker.ts', import.meta.url),
|
||||
{ type: 'module' },
|
||||
),
|
||||
);
|
||||
|
||||
const fetchWorker: typeof fetch = async (input) => {
|
||||
const url = input instanceof Request ? input.url : input.toString();
|
||||
|
||||
const args = await _worker.fetch(url);
|
||||
return new Response(...args);
|
||||
};
|
||||
|
||||
export { fetchWorker };
|
||||
17
src/workers/fetch.worker.ts
Normal file
17
src/workers/fetch.worker.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Comlink } from '@/deps.ts';
|
||||
|
||||
export const FetchWorker = {
|
||||
async fetch(url: string): Promise<[BodyInit, ResponseInit]> {
|
||||
const response = await fetch(url);
|
||||
return [
|
||||
await response.text(),
|
||||
{
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: Array.from(response.headers.entries()),
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
Comlink.expose(FetchWorker);
|
||||
Reference in New Issue
Block a user