44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import type { D1Database } from '@cloudflare/workers-types'
|
|
import { drizzle, type DrizzleD1Database } from 'drizzle-orm/d1'
|
|
import * as schema from './schema'
|
|
|
|
type DbClient = DrizzleD1Database<typeof schema>
|
|
|
|
let dbInstance: DbClient | null = null
|
|
|
|
function isQueryLoggingDisabled(): boolean {
|
|
const flag = (globalThis as any).ENV?.DRIZZLE_LOG ?? (globalThis as any).process?.env?.DRIZZLE_LOG
|
|
return flag === false || flag === 'false' || flag === '0'
|
|
}
|
|
|
|
const queryLogger = {
|
|
logQuery(query: string, params: unknown[]): void {
|
|
if (params?.length) {
|
|
console.log(`[drizzle] ${query}`, params)
|
|
} else {
|
|
console.log(`[drizzle] ${query}`)
|
|
}
|
|
},
|
|
}
|
|
|
|
export function initDb(database: D1Database): void {
|
|
const base = drizzle(database, {
|
|
schema,
|
|
// logger: isQueryLoggingDisabled() ? undefined : queryLogger,
|
|
}) as DbClient
|
|
dbInstance = Object.assign(base, {
|
|
transaction: async <T>(handler: (tx: DbClient) => Promise<T>): Promise<T> => {
|
|
return handler(base)
|
|
},
|
|
})
|
|
}
|
|
|
|
export const db = new Proxy({} as DbClient, {
|
|
get(_target, prop: keyof DbClient) {
|
|
if (!dbInstance) {
|
|
throw new Error('D1 database not initialized. Call initDb(env.DB) before using db helpers.')
|
|
}
|
|
|
|
return dbInstance[prop]
|
|
},
|
|
})
|