2025-11-27 22:15:38 +00:00
|
|
|
/**
|
|
|
|
|
* Database connection singleton
|
2025-11-27 23:47:33 +00:00
|
|
|
*
|
|
|
|
|
* SmartData models need a db reference at class definition time via lazy getter.
|
|
|
|
|
* The actual .init() is called later when the server starts.
|
2025-11-27 22:15:38 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import * as plugins from '../plugins.ts';
|
2025-11-27 23:47:33 +00:00
|
|
|
import { User } from './user.ts';
|
2025-11-27 22:15:38 +00:00
|
|
|
|
2025-11-27 23:47:33 +00:00
|
|
|
// 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;
|
2025-11-27 22:15:38 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Initialize database connection
|
|
|
|
|
*/
|
2025-11-27 23:47:33 +00:00
|
|
|
export async function initDb(
|
|
|
|
|
mongoDbUrl: string,
|
|
|
|
|
mongoDbName?: string
|
|
|
|
|
): Promise<plugins.smartdata.SmartdataDb> {
|
|
|
|
|
if (isInitialized && db) {
|
|
|
|
|
return db;
|
2025-11-27 22:15:38 +00:00
|
|
|
}
|
|
|
|
|
|
2025-11-27 23:47:33 +00:00
|
|
|
// Create the database instance with actual configuration
|
|
|
|
|
db = new plugins.smartdata.SmartdataDb({
|
|
|
|
|
mongoDbUrl: mongoDbUrl,
|
|
|
|
|
mongoDbName: mongoDbName || 'stackregistry',
|
2025-11-27 22:15:38 +00:00
|
|
|
});
|
|
|
|
|
|
2025-11-27 23:47:33 +00:00
|
|
|
await db.init();
|
|
|
|
|
isInitialized = true;
|
2025-11-27 22:15:38 +00:00
|
|
|
console.log('Database connected successfully');
|
|
|
|
|
|
2025-11-27 23:47:33 +00:00
|
|
|
// Seed default admin user if none exists
|
|
|
|
|
try {
|
|
|
|
|
await User.seedDefaultAdmin();
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.warn('[Database] Failed to seed default admin:', err);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return db;
|
2025-11-27 22:15:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2025-11-27 23:47:33 +00:00
|
|
|
* Get database instance (for backward compatibility)
|
2025-11-27 22:15:38 +00:00
|
|
|
*/
|
|
|
|
|
export function getDb(): plugins.smartdata.SmartdataDb {
|
2025-11-27 23:47:33 +00:00
|
|
|
return db;
|
2025-11-27 22:15:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Close database connection
|
|
|
|
|
*/
|
|
|
|
|
export async function closeDb(): Promise<void> {
|
2025-11-27 23:47:33 +00:00
|
|
|
if (db && isInitialized) {
|
|
|
|
|
await db.close();
|
|
|
|
|
isInitialized = false;
|
2025-11-27 22:15:38 +00:00
|
|
|
console.log('Database connection closed');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Check if database is connected
|
|
|
|
|
*/
|
|
|
|
|
export function isDbConnected(): boolean {
|
2025-11-27 23:47:33 +00:00
|
|
|
return isInitialized;
|
2025-11-27 22:15:38 +00:00
|
|
|
}
|