-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinit.js
69 lines (63 loc) · 2.53 KB
/
init.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
let isMasterThread = false;
// First example function
exports.startInitialize = async (isMaster, callback, ...next) => {
isMasterThread = isMaster; // Set master thread option for cluster mode
console.log(`[${new Date().toLocaleString()}] Starting the server...`);
if (next.length) next[0](callback, ...next.slice(1));
else callback((null, 'Nothing to initialize'));
}
// Empty initializer for non-master threads
exports.skipInitialize = async (callback, ...next) => {
if (next.length) next[0](callback, ...next.slice(1));
else callback(null, 'Step skipped');
}
// Init Database [All threads]
exports.initSequelize = (sequelizeInstance) => async (callback, ...next) => {
try {
await sequelizeInstance.authenticate();
if (next.length) next[0](callback, ...next.slice(1));
else callback((null, 'Connection with DB has been established successfully.'));
} catch (error) {
callback(error, null);
}
}
// Sync all DB tables [Master only]
exports.syncDBTables = (modelsPath, syncParams) => async (callback, ...next) => {
if (!isMasterThread) return exports.skipInitialize(callback, ...next);
try {
let BaseModel = require(`${modelsPath}/BaseModel`);
// Find all files in dir
for (let fileName of require('fs').readdirSync(modelsPath)) {
try {
// Try to check instanceof
let thisModule = require(`${modelsPath}/${fileName}`);
if (new thisModule() instanceof BaseModel.BaseModel) {
// Sync if instance is needed model
await thisModule.sync(syncParams);
}
}
catch (ex) { }
}
// Go to next init functions
if (next.length) next[0](callback, ...next.slice(1));
else callback((null, 'All DB tables were sync successfully.'));
} catch (error) {
callback(error, null);
}
}
// Init nodemailer [Master only]
exports.initMailer = (mailerInstance) => async (callback, ...next) => {
if (!isMasterThread) return exports.skipInitialize(callback, ...next);
try {
await mailerInstance.verify();
if (next.length) next[0](callback, ...next.slice(1));
else callback(null, 'NodeMailer has been started.');
} catch (error) {
callback(error, null);
}
}
// Check if .env is correctly set up
// exports.initEnvironment = async (callback, ...next) => {
// if (next.length) next[0](callback, ...next.slice(1));
// else callback(null, 'Environment initialized successfully.');
// }