-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.js
71 lines (61 loc) · 2.02 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
const fs = require('fs');
const path = require('path');
const express = require('express');
const config = require('./config');
const slugify = require('slugify');
const errorHandler = require('./middleware/errorHandler');
class Server {
constructor() {
this.app = express();
this.middleware();
this.loadRoutes();
this.startServer();
this.handleErrors();
}
middleware() {
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(errorHandler);
this.app.use((req, res, next) => {
req.config = config;
next();
});
}
loadRoutes() {
// Route to get config data
this.app.get('/config-data', (req, res) => {
res.json(req.config.motivationConfig);
});
// Serve static assets
this.app.use(express.static(path.resolve(__dirname, './public')));
// Using basic html, js, and css files for now, just load routes automatically from the public folder
fs.readdirSync(path.resolve(__dirname, './public')).forEach((file) => {
if (file.endsWith('.html')) {
const filePath = path.resolve(__dirname, `./public/${file}`);
console.log(`Loading route from: ${filePath}`);
let routeName = file.split('.')[0]; // Use the file name as the route name
routeName = slugify(routeName, { lower: true }); // Make url friendly
// Create a route for the file name without the .html extension
this.app.get('/' + routeName, (req, res) => {
res.sendFile(filePath);
});
// Create a route for the file name with the .html extension
this.app.get('/' + routeName + '.html', (req, res) => {
res.sendFile(filePath);
});
}
});
}
startServer() {
this.app.listen(config.port, () => {
console.log('Express app listening on port ' + config.port);
});
}
handleErrors() {
this.app.use((err, req, res, next) => {
console.log(err);
res.status(500).send('Something went wrong');
});
}
}
module.exports = Server;