62 lines
1.3 KiB
TypeScript
62 lines
1.3 KiB
TypeScript
import { Database } from 'bun:sqlite';
|
|
import locationTables, * as locationQueries from './location';
|
|
export * 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;
|
|
}
|