2022-02-24 03:23:54 +08:00
|
|
|
import {
|
|
|
|
AuthMechanism,
|
|
|
|
Collection,
|
|
|
|
Db,
|
|
|
|
MongoClient,
|
|
|
|
MongoClientOptions,
|
|
|
|
} from "mongodb";
|
2022-03-27 23:29:11 +08:00
|
|
|
import Logger from "../utils/logger";
|
2022-02-03 02:26:43 +08:00
|
|
|
|
|
|
|
class DatabaseClient {
|
2022-03-08 00:10:07 +08:00
|
|
|
static mongoClient: MongoClient;
|
|
|
|
static db: Db;
|
2022-03-02 00:11:01 +08:00
|
|
|
static collections: Record<string, Collection<any>> = {};
|
2022-02-03 02:26:43 +08:00
|
|
|
static connected = false;
|
|
|
|
|
2022-02-24 03:23:54 +08:00
|
|
|
static async connect(): Promise<void> {
|
2022-02-03 02:26:43 +08:00
|
|
|
const {
|
|
|
|
DB_USERNAME,
|
|
|
|
DB_PASSWORD,
|
|
|
|
DB_AUTH_MECHANISM,
|
|
|
|
DB_AUTH_SOURCE,
|
|
|
|
DB_URI,
|
|
|
|
DB_NAME,
|
|
|
|
} = process.env;
|
|
|
|
|
2022-03-08 00:10:07 +08:00
|
|
|
if (!DB_URI || !DB_NAME) {
|
|
|
|
throw new Error("No database configuration provided");
|
|
|
|
}
|
|
|
|
|
2022-02-24 03:23:54 +08:00
|
|
|
const connectionOptions: MongoClientOptions = {
|
2022-02-03 02:26:43 +08:00
|
|
|
connectTimeoutMS: 2000,
|
|
|
|
serverSelectionTimeoutMS: 2000,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (DB_USERNAME && DB_PASSWORD) {
|
|
|
|
connectionOptions.auth = {
|
|
|
|
username: DB_USERNAME,
|
|
|
|
password: DB_PASSWORD,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (DB_AUTH_MECHANISM) {
|
2022-02-24 03:23:54 +08:00
|
|
|
connectionOptions.authMechanism = DB_AUTH_MECHANISM as AuthMechanism;
|
2022-02-03 02:26:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (DB_AUTH_SOURCE) {
|
|
|
|
connectionOptions.authSource = DB_AUTH_SOURCE;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.mongoClient = new MongoClient(DB_URI, connectionOptions);
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this.mongoClient.connect();
|
|
|
|
this.db = this.mongoClient.db(DB_NAME);
|
|
|
|
this.connected = true;
|
|
|
|
} catch (error) {
|
2022-03-27 23:29:11 +08:00
|
|
|
Logger.error(error.message);
|
|
|
|
Logger.error(
|
2022-02-03 02:26:43 +08:00
|
|
|
"Failed to connect to database. Exiting with exit status code 1."
|
|
|
|
);
|
|
|
|
process.exit(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-24 03:23:54 +08:00
|
|
|
static async close(): Promise<void> {
|
2022-02-03 02:26:43 +08:00
|
|
|
if (this.connected) {
|
|
|
|
await this.mongoClient.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-02 00:11:01 +08:00
|
|
|
static collection<T>(collectionName: string): Collection<T> {
|
2022-02-03 02:26:43 +08:00
|
|
|
if (!(collectionName in this.collections)) {
|
2022-03-02 00:11:01 +08:00
|
|
|
this.collections[collectionName] = this.db.collection<T>(collectionName);
|
2022-02-03 02:26:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return this.collections[collectionName];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-23 03:55:48 +08:00
|
|
|
export default DatabaseClient;
|