This commit is contained in:
Tom Moor
2017-10-22 17:16:57 -07:00
parent aceaf261d2
commit 802ce10f14
10 changed files with 146 additions and 149 deletions

View File

@ -1,49 +1,27 @@
// @flow
import React from 'react';
import path from 'path';
import fs from 'fs';
import httpErrors from 'http-errors';
import Koa from 'koa';
import Router from 'koa-router';
import sendfile from 'koa-sendfile';
import ReactDOMServer from 'react-dom/server';
import subdomainRedirect from './middlewares/subdomainRedirect';
import { Helmet } from 'react-helmet';
import renderpage from './utils/renderpage';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
import Layout from './pages/components/Layout';
import Home from './pages/Home';
import About from './pages/About';
import Pricing from './pages/Pricing';
const isProduction = process.env.NODE_ENV === 'production';
const koa = new Koa();
const router = new Router();
const sheet = new ServerStyleSheet();
const readFile = src => {
return new Promise((resolve, reject) => {
fs.readFile(src, { encoding: 'utf8' }, (err, data) => {
if (err) return reject(err);
resolve(data);
});
});
};
const renderPage = children => {
const html = ReactDOMServer.renderToString(
<StyleSheetManager sheet={sheet.instance}>
<Layout>
{children}
</Layout>
</StyleSheetManager>
);
// helmet returns an object of meta tags with toString methods, urgh.
const helmet = Helmet.renderStatic();
let head = '';
Object.keys(helmet).forEach(key => (head += helmet[key].toString()));
return html
.replace('{{CSS}}', sheet.getStyleTags())
.replace('{{HEAD}}', head);
const renderapp = async ctx => {
if (isProduction) {
await sendfile(ctx, path.join(__dirname, '../dist/index.html'));
} else {
await sendfile(ctx, path.join(__dirname, './static/dev.html'));
}
};
router.get('/_health', ctx => (ctx.body = 'OK'));
@ -61,33 +39,28 @@ if (process.env.NODE_ENV === 'production') {
});
}
// static pages
router.get('/about', ctx => renderpage(ctx, <About />));
router.get('/pricing', ctx => renderpage(ctx, <Pricing />));
// home page
router.get('/', async ctx => {
if (ctx.cookies.get('loggedIn')) {
if (isProduction) {
ctx.body = await readFile(path.join(__dirname, '../dist/index.html'));
} else {
ctx.body = await readFile(path.join(__dirname, './static/dev.html'));
}
await renderapp(ctx);
} else {
ctx.body = await renderPage(<Home />);
await renderpage(ctx, <Home />);
}
if (!ctx.status) ctx.throw(httpErrors.NotFound());
});
// catch all for react app
router.get('*', async ctx => {
if (isProduction) {
ctx.body = await readFile(path.join(__dirname, '../dist/index.html'));
} else {
ctx.body = await readFile(path.join(__dirname, './static/dev.html'));
}
await renderapp(ctx);
if (!ctx.status) ctx.throw(httpErrors.NotFound());
});
// middleware
koa.use(subdomainRedirect());
koa.use(router.routes());
// 404 handler
koa.use(async () => {
throw httpErrors.NotFound();
});