Files
registry/ts/models/db.ts

58 lines
1.2 KiB
TypeScript
Raw Normal View History

/**
* Database connection singleton
*/
import * as plugins from '../plugins.ts';
let dbInstance: plugins.smartdata.SmartdataDb | null = null;
/**
* Initialize database connection
*/
export async function initDb(config: {
mongoDbUrl: string;
mongoDbName?: string;
}): Promise<plugins.smartdata.SmartdataDb> {
if (dbInstance) {
return dbInstance;
}
dbInstance = new plugins.smartdata.SmartdataDb({
mongoDbUrl: config.mongoDbUrl,
mongoDbName: config.mongoDbName || 'stackregistry',
});
await dbInstance.init();
console.log('Database connected successfully');
return dbInstance;
}
/**
* Get database instance (must call initDb first)
*/
export function getDb(): plugins.smartdata.SmartdataDb {
if (!dbInstance) {
throw new Error('Database not initialized. Call initDb() first.');
}
return dbInstance;
}
/**
* Close database connection
*/
export async function closeDb(): Promise<void> {
if (dbInstance) {
await dbInstance.close();
dbInstance = null;
console.log('Database connection closed');
}
}
/**
* Check if database is connected
*/
export function isDbConnected(): boolean {
return dbInstance !== null;
}