-
Notifications
You must be signed in to change notification settings - Fork 7
/
BaseWebServer.js
108 lines (88 loc) · 2.45 KB
/
BaseWebServer.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
module.exports = function (
express,
DefaultMiddleware,
PromiseMiddleware,
Logger,
Promise,
ErrorMiddleware,
config,
ControllerRegistration,
WinstonRequestLoggingMiddleware,
) {
class BaseWebServer {
constructor() {
this.app = express();
}
getPort() {
return this.server?.address()?.port ?? config.Port;
}
registerDefaultMiddleware() {
this.logSectionHeader('Default Middleware Registration');
DefaultMiddleware.configure(this.app);
}
registerLoggingMiddleware() {
this.logSectionHeader('Logging Middleware Registration');
WinstonRequestLoggingMiddleware.configure(this.app);
}
registerMiddleware() {
this.registerLoggingMiddleware();
this.registerStaticMiddleware();
this.registerDefaultMiddleware();
this.registerTemplatingEngine();
PromiseMiddleware.configure(this.app);
this.registerControllers();
}
registerStaticMiddleware() {}
registerTemplatingEngine() {}
registerControllers() {
this.logSectionHeader('Controller Registration');
ControllerRegistration.register(this.app);
}
registerErrorMiddleware() {
this.logSectionHeader('Error Middleware Registration');
ErrorMiddleware.configure(this.app);
}
setCluster(cluster) {
this.cluster = cluster;
}
start() {
this.registerMiddleware();
this.registerErrorMiddleware();
return this.startInternal();
}
startInternal() {
// eslint-disable-next-line no-unused-vars
return new Promise((resolve, reject) => {
this.server = this.app.listen(config.Port, () => {
Logger.info(this.startedMessage());
resolve();
});
return Promise.promisifyAll(this.server);
});
}
stop() {
return this.getCloseAsync().finally(() => {
Logger.info('Express server stopped');
});
}
getCloseAsync() {
if (this.server?.closeAsync) {
return this.server.closeAsync();
}
return Promise.resolve();
}
startedMessage() {
const port = this.getPort();
if (this.cluster) {
return `Worker ${this.cluster.worker.id} started on port ${port}`;
}
return `Express app started on port ${port}`;
}
logSectionHeader(message) {
Logger.log('========================');
Logger.info(`= ${message}`);
Logger.log('========================');
}
}
return BaseWebServer;
};