mirror of
https://github.com/aljazceru/ditto.git
synced 2026-01-19 21:34:22 +01:00
Rewrite SqliteWorker with Comlink
This commit is contained in:
@@ -1,15 +1,18 @@
|
||||
import { Comlink } from '@/deps.ts';
|
||||
|
||||
import type { SqliteWorker as _SqliteWorker } from './sqlite.worker.ts';
|
||||
import type { CompiledQuery, QueryResult } from '@/deps.ts';
|
||||
|
||||
class SqliteWorker {
|
||||
#path: string;
|
||||
#worker: Worker;
|
||||
ready: Promise<void>;
|
||||
#client: ReturnType<typeof Comlink.wrap<typeof _SqliteWorker>>;
|
||||
#ready: Promise<void>;
|
||||
|
||||
constructor(path: string) {
|
||||
this.#path = path;
|
||||
constructor() {
|
||||
this.#worker = new Worker(new URL('./sqlite.worker.ts', import.meta.url).href, { type: 'module' });
|
||||
this.#client = Comlink.wrap<typeof _SqliteWorker>(this.#worker);
|
||||
|
||||
this.ready = new Promise<void>((resolve) => {
|
||||
this.#ready = new Promise<void>((resolve) => {
|
||||
const handleEvent = (event: MessageEvent) => {
|
||||
if (event.data[0] === 'ready') {
|
||||
this.#worker.removeEventListener('message', handleEvent);
|
||||
@@ -20,37 +23,18 @@ class SqliteWorker {
|
||||
});
|
||||
}
|
||||
|
||||
async open(): Promise<void> {
|
||||
await this.ready;
|
||||
return this.#call(['open', [this.#path]]);
|
||||
async open(path: string): Promise<void> {
|
||||
await this.#ready;
|
||||
return this.#client.open(path);
|
||||
}
|
||||
|
||||
async executeQuery<R>({ sql, parameters }: CompiledQuery): Promise<QueryResult<R>> {
|
||||
await this.ready;
|
||||
return this.#call(['query', [sql, parameters]]);
|
||||
async executeQuery<R>(query: CompiledQuery): Promise<QueryResult<R>> {
|
||||
await this.#ready;
|
||||
return this.#client.executeQuery(query) as Promise<QueryResult<R>>;
|
||||
}
|
||||
|
||||
#call<T>(msg: [string, unknown[]]): Promise<T> {
|
||||
const id = crypto.randomUUID();
|
||||
|
||||
this.#worker.postMessage([id, msg]);
|
||||
|
||||
// TODO: use a hashmap instead of an event listener for better performance.
|
||||
return new Promise((resolve) => {
|
||||
const handleEvent = (event: MessageEvent<[string, T]>) => {
|
||||
const [_id, result] = event.data;
|
||||
if (_id === id) {
|
||||
this.#worker.removeEventListener('message', handleEvent);
|
||||
resolve(result);
|
||||
}
|
||||
};
|
||||
this.#worker.addEventListener('message', handleEvent);
|
||||
});
|
||||
}
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async destroy() {
|
||||
this.#worker.terminate();
|
||||
destroy(): Promise<void> {
|
||||
return this.#client.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user