-
Notifications
You must be signed in to change notification settings - Fork 2
/
controller.ts
110 lines (94 loc) · 2.08 KB
/
controller.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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { GridFSBucket, MongoClient, Db, connect } from 'mongodb';
import { DatabaseConnectionError } from '../workerErrors';
/**
* Database connection singleton
*/
export class DatabaseController {
/**
* MongoDB client
*/
private db: Db;
/**
* Mongo connection
*/
private connection: MongoClient;
/**
* MongoDB connection URI
*/
private readonly connectionUri: string;
/**
* GridFSBucket object
* Used to store files in GridFS
*/
private gridFsBucket: GridFSBucket;
/**
* Creates controller instance
*
* @param connectionUri - mongo URI for connection
*/
constructor(connectionUri: string) {
if (!connectionUri) {
throw new DatabaseConnectionError('Connection URI is not specified. Check .env');
}
this.connectionUri = connectionUri;
}
/**
* Connect to database
* Requires `MONGO_DSN` environment variable to be set
*
* @throws {Error} if `MONGO_DSN` is not set
*/
public async connect(): Promise<Db> {
if (this.db) {
return;
}
try {
this.connection = await connect(this.connectionUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
this.db = await this.connection.db();
return this.db;
} catch (err) {
throw new DatabaseConnectionError(err);
}
}
/**
* Close connection
*
* @returns {Promise<void>}
*/
public async close(): Promise<void> {
this.db = null;
if (!this.connection) {
return;
}
this.gridFsBucket = null;
return this.connection.close();
}
/**
* @returns {*|null}
*/
public getConnection(): Db {
return this.db;
}
/**
* Prepares GridFs bucket to store files
*
* @param {string} name - The bucket name. Defaults to 'fs'.
*/
public createGridFsBucket(name: string): GridFSBucket {
this.gridFsBucket = new GridFSBucket(this.db, {
bucketName: name,
});
return this.gridFsBucket;
}
/**
* Returns GridFs Bucket
*
* @returns {GridFSBucket}
*/
public getBucket(): GridFSBucket {
return this.gridFsBucket;
}
}