feat: use D1 binding for local database
This commit is contained in:
@@ -1,19 +1,12 @@
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getRequestEvent } from '$app/server';
|
||||
import { createClient, type Client } from '@libsql/client';
|
||||
import { drizzle as drizzleD1, type DrizzleD1Database } from 'drizzle-orm/d1';
|
||||
import { drizzle as drizzleLibSQL, type LibSQLDatabase } from 'drizzle-orm/libsql';
|
||||
import * as schema from './schema';
|
||||
|
||||
type Schema = typeof schema;
|
||||
type LocalDatabase = LibSQLDatabase<Schema> & { $client: Client };
|
||||
type D1DatabaseClient = DrizzleD1Database<Schema> & { $client: D1Database };
|
||||
|
||||
export type Database = LocalDatabase;
|
||||
export type RuntimeDatabase = LocalDatabase | D1DatabaseClient;
|
||||
export type Database = DrizzleD1Database<Schema> & { $client: D1Database };
|
||||
|
||||
let localDb: LocalDatabase | undefined;
|
||||
const d1Databases = new WeakMap<D1Database, D1DatabaseClient>();
|
||||
const d1Databases = new WeakMap<D1Database, Database>();
|
||||
|
||||
function getD1Binding() {
|
||||
try {
|
||||
@@ -23,17 +16,6 @@ function getD1Binding() {
|
||||
}
|
||||
}
|
||||
|
||||
function getLocalDb() {
|
||||
if (localDb) return localDb;
|
||||
if (!env.DATABASE_URL)
|
||||
throw new Error('DATABASE_URL is not set and no Cloudflare D1 DB binding is available');
|
||||
|
||||
const client = createClient({ url: env.DATABASE_URL });
|
||||
localDb = drizzleLibSQL(client, { schema });
|
||||
|
||||
return localDb;
|
||||
}
|
||||
|
||||
function getD1Db(binding: D1Database) {
|
||||
const cached = d1Databases.get(binding);
|
||||
if (cached) return cached;
|
||||
@@ -44,13 +26,11 @@ function getD1Db(binding: D1Database) {
|
||||
return database;
|
||||
}
|
||||
|
||||
export function getDb(): RuntimeDatabase {
|
||||
if (env.DATABASE_URL) return getLocalDb();
|
||||
|
||||
export function getDb(): Database {
|
||||
const d1Binding = getD1Binding();
|
||||
if (d1Binding) return getD1Db(d1Binding);
|
||||
|
||||
return getLocalDb();
|
||||
throw new Error('Cloudflare D1 DB binding is not available');
|
||||
}
|
||||
|
||||
export const db = new Proxy({} as Database, {
|
||||
|
||||
Reference in New Issue
Block a user