@warlock.js/cascade
Version:
ORM for managing databases
101 lines (100 loc) • 3.44 kB
JavaScript
import {colors}from'@mongez/copper';import events from'@mongez/events';import {log}from'@warlock.js/logger';import {MongoClient}from'mongodb';import {setDatabaseConfigurations}from'./config.js';import {database,Database}from'./database.js';class Connection {
/**
* Mongo Client
*/
client;
/**
* Database instance
*/
database;
/**
* A flag to check if the connection is established
*/
isConnectionEstablished = false;
/**
* Database configurations
*/
configurations = {
host: "localhost",
port: 27017,
username: "",
password: "",
database: "",
dbAuth: "",
};
/**
* Connect to the database
*/
async connect(databaseConfigurations) {
if (this.isConnectionEstablished)
return;
if (databaseConfigurations) {
this.configurations = {
...this.configurations,
...databaseConfigurations,
};
setDatabaseConfigurations(this.configurations);
}
const { host, port, username, password, database: databaseName, dbAuth, url, ...otherConnectionOptions } = this.configurations;
try {
log.info("database", "connection", `Connecting to the database ${colors.goldBright(databaseName)}`);
//
const { model: _, ...connectionOptions } = otherConnectionOptions;
if (dbAuth) {
connectionOptions.authSource = dbAuth;
}
if (username && password && !url) {
connectionOptions.auth = {
username,
password,
};
}
this.client = await MongoClient.connect(url || `mongodb://${host}:${port}`, connectionOptions);
const mongoDBDatabase = await this.client.db(databaseName);
this.database = database.setDatabase(mongoDBDatabase).setConnection(this);
this.isConnectionEstablished = true;
// listen on connection close
this.client.on("close", () => {
this.trigger("close", this);
});
if (!url && (!username || !password)) {
log.warn("database", "connection", "Connected, but you are not making a secure authenticated connection!");
}
else {
log.success("database", "connection", "Connected to the database");
}
this.trigger("connected", this);
}
catch (error) {
log.error("database", "connection", error);
this.trigger("error", error);
}
}
/**
* Check if the connection is established
*/
isConnected() {
return this.isConnectionEstablished;
}
/**
* Trigger the given event
*/
trigger(eventName, ...args) {
return events.trigger(`database.connection.${eventName}`, ...args);
}
/**
* Subscribe to one of connection events
*/
on(eventName, callback) {
return events.subscribe(`database.connection.${eventName}`, callback);
}
/**
* Use another database
*/
useDatabase(name) {
return new Database()
.setDatabase(this.client.db(name))
.setConnection(this);
}
}
const connection = new Connection();export{Connection,connection};//# sourceMappingURL=connection.js.map