Initial commit
This commit is contained in:
60
packages/concierge-bot/src/lib/db/index.ts
Normal file
60
packages/concierge-bot/src/lib/db/index.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { Database } from 'bun:sqlite';
|
||||
import locationTables, * as locationQueries from './location';
|
||||
|
||||
let db: Database = undefined;
|
||||
const queries = {
|
||||
...locationQueries,
|
||||
};
|
||||
|
||||
function createTables() {
|
||||
locationTables.createTable(db!);
|
||||
}
|
||||
|
||||
function dropTables() {
|
||||
locationTables.dropTable(db!);
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (db) {
|
||||
db.close();
|
||||
db = null;
|
||||
}
|
||||
}
|
||||
|
||||
function initializeDatabase(dbPath: string = process.env.CONCIERGE_DB_PATH || ':memory:') {
|
||||
db = new Database(dbPath);
|
||||
createTables();
|
||||
|
||||
Object.keys(queries).forEach((key) => {
|
||||
if (typeof queries[key] === 'function') {
|
||||
queries[key] = queries[key].bind(null, db);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type OmitFirstArg<F> = F extends (arg1: any, ...args: infer R) => infer Ret ? (...args: R) => Ret : never;
|
||||
|
||||
type CurriedObject<T, O> = {
|
||||
[K in keyof T]: T[K] extends (arg1: O, ...args: infer R) => infer Ret ? OmitFirstArg<T[K]> : T[K];
|
||||
};
|
||||
|
||||
export type DB = CurriedObject<Omit<typeof queries, 'default'>, Database> & {
|
||||
db: Database;
|
||||
createTables: () => void;
|
||||
dropTables: () => void;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
export function getDB(): DB {
|
||||
if (!db) {
|
||||
initializeDatabase();
|
||||
}
|
||||
return {
|
||||
...(queries as any),
|
||||
default: undefined,
|
||||
createTables,
|
||||
dropTables,
|
||||
close,
|
||||
db,
|
||||
} as DB;
|
||||
}
|
||||
Reference in New Issue
Block a user