-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconnector.ts
More file actions
93 lines (74 loc) · 2.85 KB
/
Copy pathconnector.ts
File metadata and controls
93 lines (74 loc) · 2.85 KB
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
import { connect, Connection } from 'mongoose';
import { readdirSync } from 'fs';
import getLogger from '@commons/logger';
import { dotEnv } from '@commons/dotEnvLoader';
const logger = getLogger(module.filename);
const { DATABASE_PROTOCOL, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME } = dotEnv;
const DATABASE_URL = `${DATABASE_PROTOCOL}://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}`;
const MAX_DB_CONNECTION_ATTEMPTS = 5;
const CONNECTION_ATTEMPT_TIMEOUT = 2000;
const requiredCollectionNames = readdirSync(`${__dirname}/populate/initialData`, { withFileTypes: true })
.filter((file) => file.isFile())
.map(({ name: fileName }) => {
const collectionName = fileName.match(/(?<collectionName>.*)\.json$/)?.groups?.collectionName;
if (!collectionName) {
throw Error(`Could not find collection name for file "${fileName}"!`);
}
return collectionName;
});
let dbConnection: Connection;
async function tryToConnectWithDB(attempts = 1): Promise<Connection | Error> {
logger.log(`Trying to connect with MongoDB via URL '${DATABASE_URL}' at attempt ${attempts}.`);
return new Promise((resolve: (maybeRetry?: true) => void, reject) => {
connect(
DATABASE_URL,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
},
async function (error: Error | null, connection?: Connection) {
if (error) {
logger.error('Failed to connect to MongoDB! :(\nerror:', error);
if (attempts < MAX_DB_CONNECTION_ATTEMPTS) {
return void setTimeout(() => resolve(true), CONNECTION_ATTEMPT_TIMEOUT);
}
return reject(error);
}
dbConnection = connection!;
dbConnection.on('error', (err) => logger.error('Connection error to DB occured!', err));
dbConnection.on('disconnecting', () => logger.log('Disconnecting from DB...'));
dbConnection.on('disconnected', () => logger.log('Disconnected from DB.'));
return resolve();
}
);
}).then((maybeRetry: true | void) => {
if (maybeRetry === true) {
logger.log('Retrying connection with DB...');
return tryToConnectWithDB(attempts + 1);
}
logger.log('Connected to MongoDB!');
return dbConnection;
});
}
export async function connectWithDB() {
if (dbConnection) {
return dbConnection;
}
return tryToConnectWithDB();
}
export async function getPopulationState() {
if (!dbConnection) {
return false;
}
try {
const collections = await dbConnection.db.listCollections().toArray();
const requiredCollectionsReady = requiredCollectionNames.every((reqColName) =>
collections.find(({ name }) => reqColName === name)
);
return requiredCollectionsReady;
} catch (dbPopulationStateCheckError) {
logger.error('dbPopulationStateCheckError:', dbPopulationStateCheckError);
return false;
}
}