forked from aakashkcx/eight-ball
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (77 loc) · 2.44 KB
/
index.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
// Dependencies
import http from 'http';
import logger from 'morgan';
import chalk from 'chalk';
import express from 'express';
import flash from 'connect-flash';
import { Server } from 'socket.io';
import { engine } from 'express-handlebars';
// imports
import helpers from './src/site/helpers.js';
import applySocketEvents from './src/serverSocket.js';
import authentication from './src/site/authentication.js';
import { applySecurityConfig } from './src/site/security.js';
import { configureSessionStore, initializeDatabase } from './src/db/database.js';
// Routers
import indexRouter from './src/routes/index.js';
import usersRouter from './src/routes/users.js';
// Init
const app = express();
const PORT = process.env.PORT || 8080;
const server = http.createServer(app);
await initializeDatabase();
app.use(express.urlencoded({ extended: true }));
// Security middleware
applySecurityConfig(app);
// Set port
app.set('port', PORT);
// Set view engine
app.engine('hbs', engine({
extname: '.hbs',
defaultLayout: false,
helpers: helpers,
}));
app.set('view engine', 'hbs');
// Set static path to /public
app.use(express.static('public'));
// HTTP logger middleware
app.use(logger('tiny'));
// Body parser middleware
app.use(express.json());
// socket.io with events
const io = new Server(server, {
cors: {
origin: '*',
},
});
const session = configureSessionStore(app);
// middelware wrapper to translate socket.io to express
const wrap = middleware => (socket, next) => {
middleware(socket.request, socket.request.res || new http.ServerResponse(socket.request), next);
};
io.use(wrap(session));
// socket events, like on connect and such
applySocketEvents(io);
// Authentication middleware
app.use(authentication);
// Flash messaging middleware
app.use(flash());
// Custom middleware to load preset flash messages into local variables
app.use((req, res, next) => {
res.locals.flash_success = req.flash('success');
res.locals.flash_danger = req.flash('danger');
res.locals.flash_warning = req.flash('warning');
next();
});
// Routers
app.use('/', indexRouter);
app.use('/', usersRouter);
// Invalid route
app.get('*', (_req, _res, next) => next('Page not found.'));
// Error handler
app.use((err, _req, res, _next) => res.render('error', { error: err }));
// Start the server
server.listen(PORT, () => {
console.log(chalk.bold.red('Server started...'));
console.log(chalk.bold.red(`Listening on port ${PORT}...`));
});