-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.ts
34 lines (30 loc) · 1007 Bytes
/
mongo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Collection, Db, MongoClient } from "mongodb";
export default class DBClient {
private client: MongoClient;
private database: Db | null;
private name: string;
private tables: { [name: string]: Collection }
constructor(url: string, name: string) {
this.client = new MongoClient(url);
this.database = null;
this.name = name;
this.tables = {};
}
async init() {
try {
await this.client.connect();
this.database = this.client.db(this.name);
console.log(`🔥 Connected to ${this.name} 🔥`);
} catch (err) {
console.log('Err connecting to mongo')
}
}
getClient = () => this.client
getDatabase = () => this.database
getTable = (tableName: string) => {
if (this.tables[tableName] === undefined && this.database) {
this.tables[tableName] = this.database.collection(tableName);
}
return this.tables[tableName];
};
}