-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
142 lines (116 loc) · 4.07 KB
/
app.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import cluster from 'cluster';
import { cpus } from 'node:os';
import { normalizePort, onError } from './helpers/helpers.js';
import createError from 'http-errors';
import express from 'express';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
import indexRouter from './routes/index.js';
import { router as authRouter } from './routes/auth.js';
import { router as productsRouter, productsStore } from './routes/productos.js';
import { router as productsTestRouter } from './routes/productos-test.js';
import { router as randomRouter } from './routes/random.js';
import { router as infoRouter } from './routes/info.js';
import http from 'http';
import { Server } from "socket.io";
import { config } from './config.js';
// Session Store
import session from "express-session";
import MongoStore from 'connect-mongo';
// Passport Login and Session
import { passportMiddleware, passportSessionHandler } from './middleware/passport.js';
import { mensajes } from './store/indexContenedor.js';
import { fileURLToPath } from 'url';
console.log("Procesors: ",);
const numCPUs = cpus().length;
if (cluster.isPrimary && config.SERVER_MODE == "CLUSTER") {
console.log("---> CLUSTER MODE!!!!")
console.log(`Primary ${process.pid} is running`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is online.');
});
cluster.on('exit', function (worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died.');
});
}
else {
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cookieParser());
// Session Middleware
app.use(session({
store: MongoStore.create({ mongoUrl: config.MONGO_URL, ttl: 10 * 60 }),
secret: "estoEsSecreto",
resave: false,
saveUninitialized: false,
}));
// Passport Login and Session
// app.use(sessionHandler);
app.use(passportMiddleware);
app.use(passportSessionHandler);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api/auth', authRouter);
app.use('/api/productos', productsRouter);
app.use('/api/productos-test', productsTestRouter);
app.use('/api/random', randomRouter);
app.use('/info', infoRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
let messagesContainer = [];
// Socket.io Events
io.on('connection', async (socket) => {
console.log('a user connected');
const products = await productsStore.getAll();
socket.emit('products-channel', products);
socket.on("newProduct-channel", (data) => {
console.log("Recibido: ", data);
io.emit('newProduct-channel', data);
});
socket.on("newMessage-channel", async (data) => {
if (data !== "start") {
console.log("Mensaje Recibido: ", data);
await mensajes.save(data);
}
const messages = await mensajes.getAllNormalized();
io.emit('newMessage-channel', messages);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
// console.log({process})
server.listen(config.PORT);
server.on('error', onError);
server.on('listening', () => {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
});
}