UNPKG

rwsdk

Version:

Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime

41 lines (39 loc) 1.46 kB
import { Kysely } from "kysely"; import { requestInfo, waitForRequestInfo } from "../../requestInfo/worker.js"; import { DOWorkerDialect } from "./DOWorkerDialect.js"; const createDurableObjectDb = (durableObjectBinding, name = "main") => { const durableObjectId = durableObjectBinding.idFromName(name); const stub = durableObjectBinding.get(durableObjectId); stub.initialize(); return new Kysely({ dialect: new DOWorkerDialect({ stub }), }); }; export function createDb(durableObjectBinding, name = "main") { const cacheKey = `${durableObjectBinding}_${name}`; const doCreateDb = () => { if (!requestInfo.rw) { throw new Error(` rwsdk: A database created using createDb() was accessed before requestInfo was available. Please make sure database access is happening in a request handler or action handler. `); } let db = requestInfo.rw.databases.get(cacheKey); if (!db) { db = createDurableObjectDb(durableObjectBinding, name); requestInfo.rw.databases.set(cacheKey, db); } return db; }; waitForRequestInfo().then(() => doCreateDb()); return new Proxy({}, { get(target, prop, receiver) { const db = doCreateDb(); const value = db[prop]; if (typeof value === "function") { return value.bind(db); } return value; }, }); }