mirror of
https://github.com/aljazceru/ditto.git
synced 2026-01-14 19:04:26 +01:00
DittoPglite: prevent starting PGlite instances in worker threads
This commit is contained in:
30
src/utils/worker.test.ts
Normal file
30
src/utils/worker.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { assertEquals } from '@std/assert';
|
||||
|
||||
import { isWorker } from '@/utils/worker.ts';
|
||||
|
||||
Deno.test('isWorker from the main thread returns false', () => {
|
||||
assertEquals(isWorker(), false);
|
||||
});
|
||||
|
||||
Deno.test('isWorker from a worker thread returns true', async () => {
|
||||
const script = `
|
||||
import { isWorker } from '@/utils/worker.ts';
|
||||
postMessage(isWorker());
|
||||
self.close();
|
||||
`;
|
||||
|
||||
const worker = new Worker(
|
||||
URL.createObjectURL(new Blob([script], { type: 'application/javascript' })),
|
||||
{ type: 'module' },
|
||||
);
|
||||
|
||||
const result = await new Promise<boolean>((resolve) => {
|
||||
worker.onmessage = (e) => {
|
||||
resolve(e.data);
|
||||
};
|
||||
});
|
||||
|
||||
worker.terminate();
|
||||
|
||||
assertEquals(result, true);
|
||||
});
|
||||
9
src/utils/worker.ts
Normal file
9
src/utils/worker.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Detect if this thread is running in a Worker context.
|
||||
*
|
||||
* https://stackoverflow.com/a/18002694
|
||||
*/
|
||||
export function isWorker(): boolean {
|
||||
// @ts-ignore This is fine.
|
||||
return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
|
||||
}
|
||||
Reference in New Issue
Block a user