import * as plugins from './plugins.js'; import type { TDatabaseConfig } from './skr.types.js'; /** The database skr's models are bound to, and whether skr opened it. */ interface IDatabaseBinding { db: plugins.nosqldb.SmartdataDb; /** skr opened the connection itself and closes it in closeDb() */ owned: boolean; } let binding: IDatabaseBinding | null = null; let connecting: Promise | null = null; /** An owned SmartData transaction session (`db.createSession()`). */ export type TDbSession = plugins.nosqldb.SmartdataSession; const bind = async (config: TDatabaseConfig): Promise => { if (config.db) { if (config.db.status !== 'connected') { throw new Error('The SmartdataDb handed to skr must be connected: await its init() first.'); } return { db: config.db, owned: false }; } const db = new plugins.nosqldb.SmartdataDb({ mongoDbUrl: config.mongoDbUrl, mongoDbName: config.dbName || 'skr_accounting', }); await db.init(); return { db, owned: true }; }; /** * Binds skr's models to a database: the injected one, or a connection skr * opens from the URL. The first call binds; later calls return the bound db. * Collections are prepared by `getDb()` (skr.storage.ts), not here. */ export const connectDb = async ( config?: TDatabaseConfig, ): Promise => { if (binding) { return binding.db; } if (!config) { throw new Error('Database configuration required for first initialization'); } if (!connecting) { connecting = bind(config); } try { binding = await connecting; } finally { connecting = null; } return binding.db; }; export const getDbSync = (): plugins.nosqldb.SmartdataDb => { if (!binding) { throw new Error('Database not initialized. Call getDb() first.'); } return binding.db; }; /** * Unbinds skr's models. A connection skr opened is closed; an injected * database stays open — its owner closes it. */ export const closeDb = async (): Promise => { if (!binding) { return; } const { db, owned } = binding; binding = null; if (owned) { await db.close(); } };