forked from zurichat/zc_plugin_company_files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (63 loc) · 2.62 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
75
76
77
require('colors');
require('dotenv').config();
require('express-async-errors');
const path = require('path');
const cors = require('cors');
const cpus = require('os').cpus();
const cluster = require('cluster');
const express = require('express');
const compression = require('compression');
const app = express();
const router = express.Router();
const rootRouter = require('./backend/routes/index')(router);
const isProduction = process.env.NODE_ENV === 'production';
const ErrorHandler = require('./backend/middlewares/errorHandler');
app.use(cors({ origin: ['*'] }));
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
// To serve frontend build files
app.use(express.static(path.join(__dirname, 'frontend/dist')));
app.use(express.static(path.join(__dirname, 'root-config/dist')));
app.get('/zuri-zuri-plugin-company-files.js', (req, res) => {
res.sendFile(path.join(__dirname, 'frontend/dist/zuri-zuri-plugin-company-files.js'));
});
app.get('/zuri-root-config.js', (req, res) => {
res.sendFile(path.join(__dirname, 'root-config/dist/zuri-root-config.js'));
});
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
// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
isProduction
? res.sendFile(path.join(__dirname, 'root-config/dist', 'index.html'))
: res.sendFile(path.join(__dirname, 'root-config/dist', 'index-dev.html'))
});
// For handling server errors and all other errors that might occur
app.use(ErrorHandler);
(async () => {
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.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);
});