-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
61 lines (53 loc) · 1.84 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
/**
* HTTP server for render
*/
process.env.TARGET = process.env.TARGET || 'node';
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const path = require('path');
const { Worker } = require('worker_threads');
const express = require('express');
const httpProxy = require('http-proxy');
const config = require('./src/config.js');
const proxy = httpProxy.createProxyServer({});
const app = express();
app.use(express.static(path.resolve('./dist/web'), { index: false }));
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get(/\.[a-z0-9]+$/, (req, res) => {
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('404');
});
for (const path of Object.keys(config.api.proxy)) {
console.log(`Proxy ${path} => ${config.api.proxy[path].target}`);
app.all(path, async (req, res) => {
proxy.web(req, res, config.api.proxy[path]);
});
}
app.get('/*', async (req, res) => {
try {
const result = await render({
method: req.method,
url: req.url,
headers: req.headers,
body: req.body,
});
res.writeHead(result.status, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(result.out);
} catch (e) {
console.error(e);
res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('ERROR');
}
});
app.listen(config.ssr.port, config.ssr.host);
function render(params) {
return new Promise((resolve, reject) => {
const worker = new Worker('./dist/node/main.js', { workerData: params });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', code => {
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}
console.log(`Server run on http://${config.ssr.host}:${config.ssr.port}`);