Created
March 16, 2021 09:13
-
-
Save MohammedALREAI/500d34f1ceaa1194d9a26d4d82fc9596 to your computer and use it in GitHub Desktop.
DatabaseService connection with typescript and mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import config, { IConfig } from 'config'; | |
import mongoose, { Mongoose } from 'mongoose'; | |
import {EventEmitter} from"events" | |
const dbConfig: IConfig = config.get('App.database'); | |
import Logger from'./lib/logger' | |
class DatabaseService { | |
public static emitter: EventEmitter = new EventEmitter(); | |
public static isConnected = false; | |
public static logger: any = new Logger(); | |
public static async getConnection(callback = null, wait = false) { | |
DatabaseService.handleConnectionError(); | |
return await DatabaseService.createConnection(); | |
} | |
public static async createConnection() { | |
const dbConfig = config[`${process.env.ENV}`]; | |
return await mongoose.connect(dbConfig.get('mongoUrl'), { | |
useCreateIndex: true, | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
}).then(() => { | |
DatabaseService.isConnected = true; | |
DatabaseService.logger.log('info', 'database connected successfully'); | |
}).catch((err: Error) => { | |
DatabaseService.logger.log('info', 'database connection error...retrying'); | |
DatabaseService.emitter.emit('DB_CONNECT_ERROR'); | |
}); | |
} | |
public static async handleConnectionError() { | |
DatabaseService.emitter.on('DB_CONNECT_ERROR', async () => { | |
DatabaseService.logger.log('info', 'database connection error...retrying'); | |
setTimeout(async () => { | |
await DatabaseService.createConnection(); | |
}, 3000) | |
}); | |
} | |
} | |
export { DatabaseService }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment