-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.js
More file actions
93 lines (74 loc) · 2.08 KB
/
server.js
File metadata and controls
93 lines (74 loc) · 2.08 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
const mongoose = require("mongoose");
const expressServer = require("./src/config/express");
const cluster = require("cluster");
const OS = require("os");
require("dotenv").config();
class App {
port;
databaseUrl;
constructor() {
this.validateEnvVars();
this.port = process.env.PORT || 8080;
this.databaseUrl = process.env.DATABASE_URL;
this.buildCluster();
}
validateEnvVars = () => {
const errorMessage = "Required Environment Variable:";
if (!process.env.DATABASE_URL) {
throw new Error(`${errorMessage} DATABASE_URL`);
}
if (!process.env.AUTH_ROUNDS) {
throw new Error(`${errorMessage} AUTH_ROUNDS`);
}
if (!process.env.AUTH_SECRET) {
throw new Error(`${errorMessage} AUTH_SECRET`);
}
};
database = () => {
mongoose.connect(this.databaseUrl, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("connected", () => {
console.log("Connected Database");
});
process.on("SIGINT", () => {
mongoose.connection.close(() => {
console.log("Close database connection");
process.exit(0);
});
});
mongoose.connection.on("error", (error) => {
console.log("Connection Error: " + error);
});
};
buildCluster = () => {
let workers = Number(process.env.WORKERS || 1);
if (process.env.AUTO_SCALE === "true") {
workers = this.autoScale(workers);
}
if (cluster.isMaster) {
console.log("Master Cluster Online");
for (let i = 0; i < workers; i += 1) {
console.log(`Creating instances ${workers}`);
cluster.fork();
}
cluster.on("exit", (worker) => {
console.error(`Worker ${worker.id} Offline`);
cluster.fork();
});
} else {
expressServer.listen(this.port, () => {
this.database();
console.log(`Server running on port ${this.port}`);
});
}
};
autoScale = (workersByCpu) => {
const cpus = OS.cpus().length;
const workers = cpus * workersByCpu;
return workers;
};
}
new App();