-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
84 lines (71 loc) · 2.15 KB
/
main.js
File metadata and controls
84 lines (71 loc) · 2.15 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
require('dotenv/config');
require('module-alias/register');
const fs = require('fs');
const net = require('net');
const http = require('http');
const https = require('https');
const CLITable3 = require('cli-table3');
const listEndpoints = require('express-list-endpoints');
let server;
const routes = require('@exzly-routes');
const { sequelize } = require('@exzly-models');
const { winstonLogger } = require('@exzly-utils');
const checkPortAvailability = (port) => {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.on('error', () => resolve(false));
server.on('listening', () => {
server.close();
resolve(true);
});
server.listen(port);
});
};
const tryListeningPort = async (startPort) => {
let port = startPort;
do {
const isPortAvailable = await checkPortAvailability(port);
if (isPortAvailable) {
return port;
} else {
port = port + 1;
}
} while (port <= 65535);
};
(async () => {
let chosenPort = process.env.PORT ? parseInt(process.env.PORT) : 3000;
chosenPort = await tryListeningPort(chosenPort);
if (process.env.ENABLE_HTTPS === 'true') {
const key = fs.readFileSync(process.env.SSL_KEY_FILE);
const cert = fs.readFileSync(process.env.SSL_CERT_FILE);
server = https.createServer({ key, cert }, routes);
} else {
server = http.createServer(routes);
}
server.on('listening', async () => {
if (process.env.NODE_ENV === 'development') {
await sequelize.sync({
[process.env.DB_MODE]: process.env.DB_SYNC === 'true',
});
}
const endpoints = listEndpoints(routes);
const endpointsTable = new CLITable3({
head: ['Methods', 'Path', 'Middleware'],
});
const loadEndpoint = (e = 0) => {
if (e < endpoints.length) {
endpointsTable.push([
endpoints[e].methods.join('|'),
endpoints[e].path,
endpoints[e].middlewares.length,
]);
loadEndpoint(e + 1);
}
};
loadEndpoint();
console.log(endpointsTable.toString());
winstonLogger.info(`Application started on port ${chosenPort}`);
});
server.listen(chosenPort);
})();