DDRCompanion/lib/db/client.ts
Michael Zhang dfbf923d04
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
download charts
2024-05-16 01:02:44 -05:00

45 lines
1.4 KiB
TypeScript

import type { BindParams, Database, QueryExecResult } from "sql.js";
import { RpcProvider } from "worker-rpc";
import DbWorker from "./db.worker?worker";
import { dbStatusAtom, jotaiStore } from "../../src/globals";
import { DbStatusCode } from "./constants";
const worker = new DbWorker();
const rpcProvider = new RpcProvider((message, transfer) =>
worker.postMessage(message, transfer),
);
worker.onmessage = (e) => rpcProvider.dispatch(e.data);
rpcProvider.registerSignalHandler("db", ({ status }) => {
jotaiStore.set(dbStatusAtom, (prevState) => ({ ...prevState, status }));
});
interface AsyncDatabase {
exec(sql: string, params?: BindParams): Promise<QueryExecResult[]>;
run(sql: string, params?: BindParams): Promise<Database>;
rpc(cmd: string, args: any): Promise<any>;
}
export let dbClient: AsyncDatabase;
export async function getDbClient() {
await new Promise<void>((resolve) => {
rpcProvider.registerSignalHandler(DbStatusCode.READY, () => {
resolve();
});
});
dbClient = {
async run(s: string, p?: BindParams): Promise<Database> {
return await rpcProvider.rpc("run", { s, p });
},
async exec(s: string, p?: BindParams): Promise<QueryExecResult[]> {
return await rpcProvider.rpc("exec", { s, p });
},
async rpc(cmd, args): Promise<any> {
return await rpcProvider.rpc(cmd, args);
},
};
console.log("done :3");
}