Files
registry/ts/models/db.ts

73 lines
1.7 KiB
TypeScript
Raw Normal View History

/**
* Database connection singleton
*
* SmartData models need a db reference at class definition time via lazy getter.
* The actual .init() is called later when the server starts.
*/
import * as plugins from '../plugins.ts';
import { User } from './user.ts';
// Database instance - created lazily in initDb()
// The @Collection(() => db) decorator uses a lazy getter, so db can be undefined
// until initDb() is called. Default admin is seeded after db.init() completes.
export let db: plugins.smartdata.SmartdataDb;
let isInitialized = false;
/**
* Initialize database connection
*/
export async function initDb(
mongoDbUrl: string,
mongoDbName?: string
): Promise<plugins.smartdata.SmartdataDb> {
if (isInitialized && db) {
return db;
}
// Create the database instance with actual configuration
db = new plugins.smartdata.SmartdataDb({
mongoDbUrl: mongoDbUrl,
mongoDbName: mongoDbName || 'stackregistry',
});
await db.init();
isInitialized = true;
console.log('Database connected successfully');
// Seed default admin user if none exists
try {
await User.seedDefaultAdmin();
} catch (err) {
console.warn('[Database] Failed to seed default admin:', err);
}
return db;
}
/**
* Get database instance (for backward compatibility)
*/
export function getDb(): plugins.smartdata.SmartdataDb {
return db;
}
/**
* Close database connection
*/
export async function closeDb(): Promise<void> {
if (db && isInitialized) {
await db.close();
isInitialized = false;
console.log('Database connection closed');
}
}
/**
* Check if database is connected
*/
export function isDbConnected(): boolean {
return isInitialized;
}