ironbar-persea/response.dev.js

106 lines
2.6 KiB
JavaScript
Raw Normal View History

2018-09-03 02:03:23 -05:00
const http = require('http');
const webpack = require('webpack');
const wdm = require('webpack-dev-middleware');
const whm = require('webpack-hot-middleware');
const debug = require('debug')('truss:persea');
const {webpackConfig} = require('./webpack.config');
const backendHostname = process.env.PERSEA_BACKHOST || 'persea';
const backendPort = process.env.PERSEA_BACKPORT || 8004;
const frontendHostname = process.env.PERSEA_FRONTHOST || 'localhost';
exports.Responder = class Responder {
constructor() {
const httpServer = this.server = http.createServer();
httpServer.on('listening', () => {
const address = this.address = httpServer.address();
const config = webpackConfig();
2018-09-08 22:56:39 -05:00
for (const i in config.entry) {
config.entry[i].unshift(`webpack-hot-middleware/client?path=http://${
2018-09-03 02:03:23 -05:00
frontendHostname}:${address.port
2018-09-08 22:56:39 -05:00
}/__webpack_hmr`);
}
2018-09-03 02:03:23 -05:00
const compiler = webpack(config);
this.dm = wdm(compiler, {
2018-09-08 22:56:39 -05:00
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
},
2018-09-03 02:03:23 -05:00
stats: {
chunkModules: true,
colors: true,
context: process.cwd(),
},
});
this.hm = whm(compiler, {
path: '/__webpack_hmr',
});
debug(`HTTP listening on ${JSON.stringify(address)}...`);
});
httpServer.on('request', (req, res) => {
this.dm(req, res, (error) => {
if (error) {
return console.error(error);
}
this.hm(req, res, (error) => {
if (error) {
return console.error(error);
}
});
});
});
httpServer.on('error', console.error);
2018-09-08 22:56:39 -05:00
httpServer.on('close', () => httpServer.removeAllListeners());
}
start() {
this.server.listen(backendPort);
2018-09-03 02:03:23 -05:00
}
respond({payload: {headers, url}}) {
// forward to internal HTTP
return new Promise((resolve, reject) => {
const options = {
headers,
backendHostname,
path: url,
port: this.address.port,
};
const client = http.get(options);
client.on('response', (res) => {
let data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
2018-09-08 22:56:39 -05:00
resolve({
html: data,
headers: res.headers
});
2018-09-03 02:03:23 -05:00
});
});
client.on('error', reject);
});
}
2018-09-08 22:56:39 -05:00
stop() {
this.server.close();
}
2018-09-03 02:03:23 -05:00
}