|
| 1 | +// @ts-check |
1 | 2 | const { MongoClient, ObjectId } = require('mongodb');
|
| 3 | +const { mongodb, logs } = require('@codefresh-io/cf-telemetry'); |
2 | 4 | const { getDbNameFromUri } = require('./helper');
|
3 | 5 |
|
4 | 6 | class Mongo {
|
5 | 7 | constructor() {
|
6 | 8 | this.db = undefined;
|
7 | 9 | this.ObjectId = ObjectId;
|
| 10 | + this.logger = new logs.Logger('codefresh:infra:mongo'); |
8 | 11 | }
|
9 | 12 |
|
10 | 13 | /**
|
11 | 14 | * starts the connection to mongo
|
| 15 | + * @returns {Promise<void>} |
12 | 16 | */
|
13 | 17 | async init(config) {
|
14 |
| - const clientSettings = { ...config.mongo.options }; |
15 |
| - const logger = require('cf-logs').Logger('codefresh:infra:mongo'); // eslint-disable-line |
16 |
| - this.logger = logger; |
17 |
| - |
18 |
| - const { uri } = config.mongo; |
19 |
| - const dbName = config.mongo.dbName || getDbNameFromUri(uri); |
20 |
| - const client = new MongoClient(uri, clientSettings); |
21 |
| - logger.info(`Mongo db name ${dbName}`); |
22 |
| - |
23 | 18 | try {
|
24 |
| - await client.connect(); |
25 |
| - logger.info('Mongo driver connected'); |
| 19 | + const clientSettings = { ...config.mongo.options }; |
| 20 | + const { uri } = config.mongo; |
| 21 | + const dbName = config.mongo.dbName || getDbNameFromUri(uri); |
| 22 | + this.logger.info(`Mongo db name ${dbName}`); |
| 23 | + const client = new MongoClient(uri, clientSettings); |
| 24 | + mongodb.monitorMongoDBClient(client); |
| 25 | + |
| 26 | + this.client = await client.connect(); |
| 27 | + this.logger.info('Mongo driver connected'); |
| 28 | + this.db = this.client.db(dbName); |
| 29 | + this.logger.info('Mongo db initialized'); |
26 | 30 | } catch (error) {
|
27 |
| - logger.error('Error connecting to MongoDB:', error); |
| 31 | + this.logger.error(error, 'Error connecting to MongoDB'); |
28 | 32 | throw error;
|
29 | 33 | }
|
30 |
| - |
31 |
| - this.client = client; |
32 |
| - this.db = this.client.db(dbName); |
33 |
| - logger.info('Mongo db initialized'); |
34 | 34 | }
|
35 | 35 |
|
36 | 36 |
|
37 | 37 | /**
|
38 | 38 | * stops the connection to mongo
|
| 39 | + * @returns {Promise<void>} |
39 | 40 | */
|
40 | 41 | async stop() {
|
41 |
| - if (!this.db) { |
42 |
| - return; |
43 |
| - } |
| 42 | + if (!this.client) return; |
44 | 43 | await this.client.close();
|
45 | 44 | }
|
46 | 45 |
|
| 46 | + /** |
| 47 | + * @param {string} collectionName |
| 48 | + * @returns {import('mongodb').Collection} |
| 49 | + */ |
47 | 50 | collection(collectionName) {
|
| 51 | + // @ts-ignore |
48 | 52 | return this.db.collection(collectionName);
|
49 | 53 | }
|
50 | 54 | }
|
|
0 commit comments