swadhinbiswas feat: complete DevPulse production developer operating system for Discord · 9/6/2026
4a8d707
49 lines · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { config } from "@devpulse/config";
import { logger } from "@devpulse/logger";
import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";
import * as schema from "./schema.js";

let clientInstance: ReturnType<typeof createClient> | null = null;
let dbInstance: ReturnType<typeof drizzle<typeof schema>> | null = null;

export function getDbClient(customUrl?: string, customToken?: string) {
  if (clientInstance && !customUrl) {
    return clientInstance;
  }

  const url = customUrl || config.TURSO_DATABASE_URL || "file:devpulse.db";
  const authToken = customToken || config.TURSO_AUTH_TOKEN;

  logger.info({ url: url.replace(/:[^:@]+@/, ":***@") }, "Initializing database client");

  const client = createClient({
    url,
    authToken,
  });

  if (!customUrl) {
    clientInstance = client;
  }

  return client;
}

export function getDb(customUrl?: string, customToken?: string) {
  if (dbInstance && !customUrl) {
    return dbInstance;
  }

  const client = getDbClient(customUrl, customToken);
  const db = drizzle(client, { schema });

  if (!customUrl) {
    dbInstance = db;
  }

  return db;
}

export const db = getDb();
export type Database = typeof db;