diff --git a/src/MongoDB.ts b/src/MongoDB.ts index bbd8e88..5c3a174 100644 --- a/src/MongoDB.ts +++ b/src/MongoDB.ts @@ -25,13 +25,13 @@ type MongoOptions = { */ class MongoDB { - #database: string; + #_database: string; #config: MongoOptions; #logger: ILogger; #URI: string; #db: Db | null; - #client: MongoClient; + #_client: MongoClient; constructor (server: IServer, config: MongoOptions) { @@ -46,7 +46,7 @@ class MongoDB { this.#config = config; this.#db = null; // DB connection - this.#database = database; // Which database to connect to + this.#_database = database; // Which database to connect to this.#logger = server.createLogger(this, config.loggerOptions); @@ -65,16 +65,24 @@ class MongoDB { this.#URI = `mongodb://${auth}${host}:${port}/${AUTH_DB || ''}?readPreference=secondaryPreferred`; } - this.#client = new MongoClient(this.#URI, this.#config.client); + this.#_client = new MongoClient(this.#URI, this.#config.client); // TODO figure out reconnecting to DB when connection fails - this.#client.on('error', (error) => this.#logger.error(`MongoDB error:\n${error.stack}`)) + this.#_client.on('error', (error) => this.#logger.error(`MongoDB error:\n${error.stack}`)) .on('timeout', () => this.#logger.warn(`MongoDB timed out`)) .on('close', () => this.#logger.info(`MongoDB client disconnected`)) .on('open', () => this.#logger.info(`MongoDB client connected`)); } + get database () { + return this.#_database; + } + + get client () { + return this.#_client; + } + /** * Initialises the connection to Mongo * @@ -82,11 +90,11 @@ class MongoDB { */ async init () { - this.#logger.status(`Initializing database connection to ${this.#client.options.hosts}`); + this.#logger.status(`Initializing database connection to ${this.#_client.options.hosts}`); - await this.#client.connect(); + await this.#_client.connect(); this.#logger.debug(`Connected, selecting DB`); - this.#db = await this.#client.db(this.#database); + this.#db = await this.#_client.db(this.#_database); this.#logger.status('MongoDB ready'); @@ -96,12 +104,12 @@ class MongoDB { async close () { this.#logger.status('Closing database connection'); - await this.#client.close(); + await this.#_client.close(); this.#db = null; } get mongoClient () { - return this.#client; + return this.#_client; } /** @@ -116,7 +124,7 @@ class MongoDB { if (!this.#db) throw new Error(`MongoDB not connected`); - + if (typeof db !== 'string') throw new TypeError('Expecting collection name for the first argument'); @@ -267,7 +275,7 @@ class MongoDB { throw new Error(`MongoDB not connected`); if (typeof db !== 'string') throw new TypeError('Expecting collection name for the first argument'); - + this.#logger.debug(`Incoming random query for ${db} with parameters ${inspect(filter)} and amount ${amount}`); if (amount > 100)