-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathserver.js
74 lines (60 loc) · 2.63 KB
/
server.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
require('colors');
require('dotenv').config();
require('express-async-errors');
const path = require('path');
const cpus = require('os').cpus();
const cluster = require('cluster');
const express = require('express');
const compression = require('compression');
const fileUpload = require('express-fileupload');
const app = express();
const router = express.Router();
const connectToDatabase = require('./backend/utils/db');
const rootRouter = require('./backend/routes/index')(router);
const pluginInfoRouter = require('./backend/routes/plugin.router');
const isProduction = process.env.NODE_ENV === 'production';
const ErrorHandler = require('./backend/middlewares/errorHandler');
app.use(compression()); // Node.js compression middleware
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: false })); // For parsing application/x-www-form-urlencoded
app.use(fileUpload({ createParentPath: true })); // For adding the 'req.files' property
app.use(express.static(path.resolve(__dirname, './frontend/build')));
if (isProduction) {
app.set('trust proxy', 1); // Trust first proxy
} else {
app.use(require('morgan')('dev')); // Dev logging middleware
}
app.use('/api/v1', rootRouter); // For mounting the root router on the specified path
app.use('/', pluginInfoRouter); // For mounting the plugin info router on the '/' path
// All other GET requests not handled before will return our React app
app.use((req, res, next) => {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
res.sendFile(path.join(__dirname, './frontend/build', 'index.html'));
});
// For handling server errors and all other errors that might occur
app.use(ErrorHandler);
(async () => {
// await connectToDatabase();
if (cluster.isMaster) {
// Fork workers
cpus.forEach(() => cluster.fork());
cluster.on('exit', () => cluster.fork());
} else {
// Workers can share any TCP connection
// In this case, it is an HTTP server
const port = process.env.PORT || 5500;
const server = app.listen(port, () => {
console.log(':>>'.green.bold, 'Server running in'.yellow.bold, (process.env.NODE_ENV || 'production').toUpperCase().blue.bold, 'mode, on port'.yellow.bold, `${port}`.blue.bold)
});
// Handle unhandled promise rejections
process.on('unhandledRejection', error => {
// console.log(error);
console.log(`✖ | Unhandled Rejection: ${error.message}`.red.bold);
server.close(() => process.exit(1));
})
}
})().catch(error => {
console.log(`✖ | Error: ${error.message}`.red.bold);
});