File size: 1,939 Bytes
8969f81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { MongoClient, Db, Collection } from 'mongodb';
import { config } from '../lib/config';



/**
 * Database wrapper with collection access directly on the db object.
 */
export class Database {
	private MONGO_URI:    string;
	private MONGO_DBNAME: string;
	constructor(opts: { MONGO_URI?: string, MONGO_DBNAME?: string } = {}) {
		this.MONGO_URI    = opts.MONGO_URI    || config.mongoUrl;
		this.MONGO_DBNAME = opts.MONGO_DBNAME || config.mongoDbName;
	}
	private __client: MongoClient | null = null;
	private __db: Db | null = null;
	protected static __collectionNames = [
		'docs',
	];
	docs:             Collection;
	private __promiseConnect: Promise<boolean> | null = null;
	
	
	get isReady(): boolean {
		return this.__db !== null;
	}
	
	
	private attach() {
		for (const c of Database.__collectionNames) {
			this[c] = this.__db!.collection(c);
		}
	}
	
	collection(name: string): Collection {
		return this.__db!.collection(name);
	}
	
	command(command: Object): Promise<any> {
		return this.__db!.command(command);
	}
	
	listShards(): Promise<any> {
		return this.__db!.admin().command({ listShards: 1 });
	}
	
	database(dbName?: string): Db | null {
		if (!dbName) {
			return this.__db;
		}
		return (this.__client)
			? this.__client.db(dbName)
			: null
		;
	}
	
	connect(): Promise<boolean> {
		if (!this.__promiseConnect) {
			this.__promiseConnect = MongoClient.connect(this.MONGO_URI, {
				useNewUrlParser: true,
			}).then((client) => {
				this.__client = client;
				this.__db = this.__client.db(this.MONGO_DBNAME);
				this.attach();
				return true;
			}).catch((err) => {
				console.error("Connection error", err);
				process.exit(1);
				return false;
			});
		}
		
		return this.__promiseConnect;
	}
	
	onConnect(handler: () => void) {
		this.connect().then(handler);
	}
	
	async close() {
		if (this.__client) {
			await this.__client.close();
		}
	}
}




const db = new Database();

export default db;