diff --git a/package.json b/package.json index aa660da..7d7fd53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@togethercrew.dev/db", - "version": "3.0.62", + "version": "3.0.63", "description": "All interactions with DB", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/service/databaseManager.ts b/src/service/databaseManager.ts index 43f822e..49f355b 100644 --- a/src/service/databaseManager.ts +++ b/src/service/databaseManager.ts @@ -21,6 +21,8 @@ import { type Snowflake } from 'discord.js'; export default class DatabaseManager { private static instance: DatabaseManager; private modelCache: Record = {}; + + // Singleton pattern to get the instance of DatabaseManager public static getInstance(): DatabaseManager { if (typeof DatabaseManager.instance === 'undefined') { DatabaseManager.instance = new DatabaseManager(); @@ -28,22 +30,39 @@ export default class DatabaseManager { return DatabaseManager.instance; } - public async getTenantDb(tenantId: Snowflake): Promise { - const dbName = tenantId; + // Method to get Guild Database connection + public async getGuildDb(guildId: Snowflake): Promise { + const dbName = guildId; + const db = mongoose.connection.useDb(dbName, { useCache: true }); + await this.setupModels(db, 'guild'); + return db; + } + + // Method to get Platform Database connection + public async getPlatformDb(platformId: string): Promise { + const dbName = platformId; const db = mongoose.connection.useDb(dbName, { useCache: true }); - await this.setupModels(db); + await this.setupModels(db, 'platform'); return db; } - private async setupModels(db: Connection): Promise { + // Method to setup models based on database type + private async setupModels(db: Connection, dbType: 'guild' | 'platform'): Promise { if (!this.modelCache[db.name]) { - db.model('HeatMap', heatMapSchema); - db.model('RawInfo', rawInfoSchema); - db.model('MemberActivity', MemberActivitySchema); - db.model('GuildMember', guildMemberSchema); - db.model('Channel', channelSchema); - db.model('Role', roleSchema); - this.modelCache[db.name] = true; + try { + if (dbType === 'platform') { + db.model('HeatMap', heatMapSchema); + db.model('MemberActivity', MemberActivitySchema); + } else if (dbType === 'guild') { + db.model('RawInfo', rawInfoSchema); + db.model('GuildMember', guildMemberSchema); + db.model('Channel', channelSchema); + db.model('Role', roleSchema); + } + this.modelCache[db.name] = true; + } catch (error) { + console.error(`Error setting up models for ${db.name}:`, error); + } } } }