Skip to content

Commit

Permalink
refactor: refactor the databaseManger
Browse files Browse the repository at this point in the history
  • Loading branch information
Behzad-rabiei committed Jul 11, 2024
1 parent 0feda49 commit 822a290
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions src/service/databaseManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,39 +21,48 @@ import { type Snowflake } from 'discord.js';
export default class DatabaseManager {
private static instance: DatabaseManager;
private modelCache: Record<string, boolean> = {};

// Singleton pattern to get the instance of DatabaseManager
public static getInstance(): DatabaseManager {
if (typeof DatabaseManager.instance === 'undefined') {
DatabaseManager.instance = new DatabaseManager();
}
return DatabaseManager.instance;
}

public async getGuildDb(tenantId: Snowflake): Promise<Connection> {
const dbName = tenantId;
// Method to get Guild Database connection
public async getGuildDb(guildId: Snowflake): Promise<Connection> {
const dbName = guildId;
const db = mongoose.connection.useDb(dbName, { useCache: true });
await this.setupModels(db, 'guild');
return db;
}

public async getPlatformDb(tenantId: Snowflake): Promise<Connection> {
const dbName = tenantId;
// Method to get Platform Database connection
public async getPlatformDb(platformId: Snowflake): Promise<Connection> {
const dbName = platformId;
const db = mongoose.connection.useDb(dbName, { useCache: true });
await this.setupModels(db, 'platform');
return db;
}

// Method to setup models based on database type
private async setupModels(db: Connection, dbType: 'guild' | 'platform'): Promise<void> {
if (!this.modelCache[db.name]) {
if (dbType === 'platform') {
db.model<IHeatMap>('HeatMap', heatMapSchema);
db.model<IMemberActivity>('MemberActivity', MemberActivitySchema);
} else if (dbType === 'guild') {
db.model<IRawInfo>('RawInfo', rawInfoSchema);
db.model<IGuildMember>('GuildMember', guildMemberSchema);
db.model<IChannel>('Channel', channelSchema);
db.model<IRole>('Role', roleSchema);
try {
if (dbType === 'platform') {
db.model<IHeatMap>('HeatMap', heatMapSchema);
db.model<IMemberActivity>('MemberActivity', MemberActivitySchema);
} else if (dbType === 'guild') {
db.model<IRawInfo>('RawInfo', rawInfoSchema);
db.model<IGuildMember>('GuildMember', guildMemberSchema);
db.model<IChannel>('Channel', channelSchema);
db.model<IRole>('Role', roleSchema);
}
this.modelCache[db.name] = true;
} catch (error) {
console.error(`Error setting up models for ${db.name}:`, error);
}
this.modelCache[db.name] = true;
}
}
}

0 comments on commit 822a290

Please sign in to comment.