All files / plainweb/src get-database.ts

100% Statements 30/30
75% Branches 6/8
100% Functions 2/2
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 401x       1x 1x 1x     1x   1x   1x 1x 8x 8x 1x 1x   1x 4x 4x 4x 1x 4x 4x 4x 4x 4x 1x 1x   1x 1x 1x 1x 1x 1x  
import BetterSqlite3Database from "better-sqlite3";
import {
  type BetterSQLite3Database,
  drizzle,
} from "drizzle-orm/better-sqlite3";
import { DefaultLogger, type LogWriter } from "drizzle-orm/logger";
import { getLogger } from "log";
import type { ExpandedPlainwebConfig } from "./config";
 
const log = getLogger("database");
 
let database: BetterSQLite3Database<Record<string, unknown>> | undefined;
 
class PlainwebLogWriter implements LogWriter {
  write(message: string) {
    log.debug(message);
  }
}
const logger = new DefaultLogger({ writer: new PlainwebLogWriter() });
 
export function getDatabase<T extends Record<string, unknown>>(
  config: Pick<ExpandedPlainwebConfig<T>, "database" | "nodeEnv">,
): BetterSQLite3Database<T> {
  if (database) return database as BetterSQLite3Database<T>;
  if (!config.database.dbUrl)
    throw new Error("config.database.dbUrl is required");
  const dbUrl = config.nodeEnv === "test" ? ":memory:" : config.database.dbUrl;
  log.info("db url", dbUrl);
  const connection = new BetterSqlite3Database(dbUrl);
  for (const [key, value] of Object.entries(config.database.pragma)) {
    connection.pragma(`${key} = ${value}`);
  }
 
  database = drizzle<T>(connection, {
    schema: config.database.schema,
    logger: logger,
  });
  return database as BetterSQLite3Database<T>;
}