/
worker.js
107 lines (92 loc) · 2.88 KB
/
worker.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
"use strict";
const FastBoot = require('fastboot');
const fastbootMiddleware = require('fastboot-express-middleware');
const ExpressHTTPServer = require('./express-http-server');
class Worker {
constructor(options) {
this.distPath = options.distPath;
this.httpServer = options.httpServer;
this.ui = options.ui;
this.cache = options.cache;
this.gzip = options.gzip;
this.host = options.host;
this.port = options.port;
this.username = options.username;
this.password = options.password;
this.beforeMiddleware = options.beforeMiddleware;
this.afterMiddleware = options.afterMiddleware;
this.buildSandboxGlobals = options.buildSandboxGlobals;
this.chunkedResponse = options.chunkedResponse;
if (!this.httpServer) {
this.httpServer = new ExpressHTTPServer({
ui: this.ui,
distPath: this.distPath,
cache: this.cache,
gzip: this.gzip,
host: this.host,
port: this.port,
username: this.username,
password: this.password,
beforeMiddleware: this.beforeMiddleware,
afterMiddleware: this.afterMiddleware,
buildSandboxGlobals: options.buildSandboxGlobals,
});
}
if (!this.httpServer.cache) { this.httpServer.cache = this.cache; }
if (!this.httpServer.distPath) { this.httpServer.distPath = this.distPath; }
if (!this.httpServer.ui) { this.httpServer.ui = this.ui; }
}
start() {
if (!this.distPath) {
this.middleware = this.noAppMiddleware();
} else {
this.middleware = this.buildMiddleware();
}
this.bindEvents();
this.serveHTTP();
}
bindEvents() {
process.on('message', message => this.handleMessage(message));
}
handleMessage(message) {
switch (message.event) {
case 'reload':
this.distPath = message.distPath || this.distPath;
this.ui.writeLine('Reloading the application from distPath:', this.distPath);
this.fastboot.reload({ distPath: this.distPath });
break;
case 'error':
this.error = message.error;
break;
case 'shutdown':
process.exit(0); // eslint-disable-line no-process-exit
}
}
buildMiddleware() {
this.fastboot = new FastBoot({
distPath: this.distPath,
buildSandboxGlobals: this.buildSandboxGlobals,
});
return fastbootMiddleware({
fastboot: this.fastboot,
chunkedResponse: this.chunkedResponse,
});
}
serveHTTP() {
this.ui.writeLine('starting HTTP server');
return this.httpServer.serve(this.middleware)
.then(() => {
process.send({ event: 'http-online' });
});
}
noAppMiddleware() {
return (req, res) => {
let html = '<h1>No Application Found</h1>';
if (this.error) {
html += '<pre style="color: red">' + this.error + '</pre>';
}
res.status(500).send(html);
};
}
}
module.exports = Worker;