Skip to content

Commit

Permalink
feat(demos): respond with error page for server errors in demos (#257)
Browse files Browse the repository at this point in the history
  • Loading branch information
unstubbable authored and clebert committed Jan 11, 2019
1 parent 5f8b8ec commit 97e0484
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 16 deletions.
48 changes: 33 additions & 15 deletions packages/demos/src/start-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,45 @@ import devMiddleware from 'webpack-dev-middleware';

export type MainHtmlRenderer = (port: number) => Promise<string>;

function createDocumentHtml(bodyHtml: string): string {
return `
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
${bodyHtml}
<script src="integrator.js"></script>
</body>
</html>
`;
}

export async function startServer(
webpackConfigs: webpack.Configuration[],
renderMainHtml: MainHtmlRenderer | undefined
renderMainHtml: MainHtmlRenderer | undefined,
demoName?: string
): Promise<Server> {
const port = await getPort({port: 3000});
const port = await getPort(demoName ? {port: 3000} : undefined);
const app = express();

app.get('/', async (_req, res) => {
const mainHtml = renderMainHtml ? await renderMainHtml(port) : '';

res.send(
`<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<main>${mainHtml}</main>
<script src="integrator.js"></script>
</body>
</html>`
);
try {
const mainHtml = renderMainHtml ? await renderMainHtml(port) : '';

res.send(createDocumentHtml(`<main>${mainHtml}</main>`));
} catch (error) {
const documentHtml = demoName
? createDocumentHtml(`
<div class="bp3-callout bp3-intent-danger">
<h4 class="bp3-heading">Failed to render demo "${demoName}"</h4>
<pre>${error.stack}</pre>
</div>
`)
: error;

res.send(documentHtml).status(500);
}
});

app.use(devMiddleware(webpack(webpackConfigs), {publicPath: '/'}));
Expand Down
2 changes: 1 addition & 1 deletion packages/demos/src/watch-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function loadNodeIntegrator(): MainHtmlRenderer | undefined {
}
}

startServer(loadWebpackConfigs(), loadNodeIntegrator())
startServer(loadWebpackConfigs(), loadNodeIntegrator(), demoName)
.then(server => {
const {port} = server.address() as AddressInfo;

Expand Down

0 comments on commit 97e0484

Please sign in to comment.