import {Writable} from 'stream';
import * as React from 'react';
import {renderToPipeableStream} from 'react-dom/server';
import App from '../src/App';
import {ABORT_DELAY} from './delays';
let assets = {
'main.js': '/main.js',
'main.css': '/main.css',
};
function HtmlWritable(options) {
Writable.call(this, options);
this.chunks = [];
this.html = '';
}
HtmlWritable.prototype = Object.create(Writable.prototype);
HtmlWritable.prototype.getHtml = function getHtml() {
return this.html;
};
HtmlWritable.prototype._write = function _write(chunk, encoding, callback) {
this.chunks.push(chunk);
callback();
};
HtmlWritable.prototype._final = function _final(callback) {
this.html = Buffer.concat(this.chunks).toString();
callback();
};
module.exports = function render(url, res) {
let writable = new HtmlWritable();
res.socket.on('error', error => {
console.error('Fatal', error);
});
let didError = false;
let didFinish = false;
writable.on('finish', () => {
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-type', 'text/html');
res.send(writable.getHtml());
});
const {pipe, abort} = renderToPipeableStream(<App assets={assets} />, {
bootstrapScripts: [assets['main.js']],
onAllReady() {
didFinish = true;
},
onShellReady() {
pipe(writable);
},
onShellError(x) {
res.statusCode = 500;
res.send('<!doctype><p>Error</p>');
},
onError(x) {
didError = true;
console.error(x);
},
});
setTimeout(() => {
if (!didFinish) {
abort();
}
}, ABORT_DELAY);
};