-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
100 lines (86 loc) · 2.31 KB
/
index.js
File metadata and controls
100 lines (86 loc) · 2.31 KB
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
"use strict";
const DEFAULT_PORT = 8000;
const utilities = {
getConfiguration: (port) => {
const config = require("config");
const pkg = require("./package.json");
config.name = pkg.name;
config.version = pkg.version;
config.port = port || DEFAULT_PORT;
return config;
},
configureExpress: () => {
const express = require("express");
const app = express();
return {
express,
app
};
},
configureHogan: (app) => {
const hogan = require("hogan-express");
const path = require("path");
app.engine("html", hogan);
app.set("views", path.join(__dirname, "./views"));
app.set("view engine", "html");
app.enable("view cache");
},
configureRoutes: (config, express, app) => {
const cookieParser = require("cookie-parser");
app.use(cookieParser());
app.use(express.static("./public"));
app.get("/", utilities.handleGetRoute(config));
const bodyParser = require("body-parser");
app.post("/", bodyParser.urlencoded({extended: true}), utilities.handlePostRoute(config));
},
handleGetRoute: (config) => {
return (req, res) => {
const sessionId = req.cookies.sessionId || Date.now();
if (!req.cookies.sessionId) {
res.cookie("sessionId", sessionId);
}
const viewModel = {
sessionId: sessionId,
name: config.name,
version: config.version
};
res.render("index", viewModel);
};
},
handlePostRoute: (config) => {
return (req, res) => {
const body = (req.body || {});
const viewModel = {
sessionId: req.cookies.sessionId,
name: config.name,
version: config.version,
value1: body.value1 || "",
value2: body.value2 || ""
};
res.render("index", viewModel);
};
},
startServer: (config, app) => {
const server = app.listen(config.port, () => {
console.log(`Server listening on port: ${server.address().port}`);
});
return server;
}
};
const application = {
start: (port) => {
const config = utilities.getConfiguration(port);
const { express, app } = utilities.configureExpress();
utilities.configureHogan(app);
utilities.configureRoutes(config, express, app);
return utilities.startServer(config, app);
},
utilities: utilities
};
if (require.main === module) {
const args = process.argv.slice(2);
const port = (args.length >= 1 ? args[0] : undefined);
application.start(port);
} else {
module.exports = application;
}