@kurai-io/mongo
Version:
Abstraction layer for Mongo database
77 lines (76 loc) • 2.18 kB
JavaScript
class o {
constructor(t, n) {
this.mongoClient = t, this.dbName = n;
}
_database;
/**
* Tracks the current connection status.
* @default ConnectionStatus.Disconnected
* @private
*/
_connectionStatus = 1;
/**
* Gets the current connection status.
*/
get connectionStatus() {
return this._connectionStatus;
}
/**
* Gets the name of the configured database.
*/
get databaseName() {
return this.mongoClient.db.name || null;
}
/**
* Gets the current database instance, if connected.
*/
get db() {
return this._database;
}
/**
* Gets the current database instance, cast as non-undefined.
* Use with caution; throws if not connected.
*/
get unsafeDB() {
return this._database;
}
/**
* Ensures that there is an active connection to the database.
* @throws Error if not connected
*/
checkConnection() {
if (this._connectionStatus !== 0)
throw new Error("Not connected to database");
}
/**
* Disconnects from the MongoDB server.
* If already disconnected, does nothing.
* @returns promise that resolves to true if disconnection succeeded or was unnecessary,
* or false if an error occurred during client.close()
*/
async disconnect() {
return this._connectionStatus === 1 ? !0 : await this.mongoClient.close().catch(() => null) === null ? !1 : (this._connectionStatus = 1, !0);
}
/**
* Connects to the MongoDB server and selects the database.
* If already connected, does nothing.
*/
async connect() {
if (this._connectionStatus === 0) return this;
if (!await this.mongoClient.connect().catch(() => null)) throw new Error("Cannot connect to database");
return this._database = this.mongoClient.db(this.dbName), this._connectionStatus = 0, this;
}
/**
* Retrieves a collection from the connected database.
* @typeParam T shape of the documents in the collection
* @param name name of the collection to access
* @returns MongoDB Collection instance
* @throws Error if not connected
*/
collection(t) {
return this.checkConnection(), this.unsafeDB.collection(t);
}
}
export {
o as default
};