-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.js
105 lines (76 loc) · 1.92 KB
/
database.js
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
import config from "./config.js";
import { readDotEnv } from "./env.js";
import { danger, error, muted, success } from "./colors.js";
import { createPool } from "mysql2";
const databases = {};
export function getDatabase(cluster) {
return databases[cluster];
}
export async function initDatabases(only = null) {
const promises = [];
for (const cluster of config.servers) {
if (only && cluster !== only) continue;
promises.push(initDatabase(cluster));
}
await Promise.all(promises);
console.info(success("All databases initialized successfully!"));
}
async function initDatabase(cluster) {
const cfg = readDotEnv(cluster);
if (!cfg) {
return;
}
const database = {
pool: createPool({
connectionLimit: 5,
host: cfg.DB_HOST,
port: cfg.DB_PORT,
user: cfg.DB_USERNAME,
password: cfg.DB_PASSWORD,
database: cfg.DB_DATABASE,
}),
};
database.query = (query, values = []) =>
new Promise((resolve, reject) => {
database.pool.getConnection((err, conn) => {
if (err) {
reject(err);
logDatabaseError(cluster, err, query);
return;
}
conn.query(query, values, (err, rows) => {
conn.release();
if (err) {
reject(err);
logDatabaseError(cluster, err, query);
return;
}
resolve(rows);
});
});
});
if (!(await testConnection(database))) {
console.warn(`Failed to connect to database ${cluster}, trying again in 5 minutes...`);
setTimeout(
() => {
initDatabase(cluster);
},
5 * 60 * 1000
);
return;
}
databases[cluster] = database;
console.log(success(`Successfully connected to database for ${cluster}...`));
}
async function testConnection(database) {
try {
await database.query("SELECT 1");
return true;
} catch {
// Don't care
}
return false;
}
function logDatabaseError(cluster, err, query) {
console.error(`${danger(`${cluster} database error`)}\n - ${muted(query)}\n - ${error(err.message)}`);
}