2016-04-29 05:25:37 +00:00
|
|
|
const path = require('path');
|
|
|
|
import httpErrors from 'http-errors';
|
|
|
|
import Koa from 'koa';
|
|
|
|
import Router from 'koa-router';
|
|
|
|
import sendfile from 'koa-sendfile';
|
|
|
|
|
2016-05-27 07:06:36 +00:00
|
|
|
import subdomainRedirect from './middlewares/subdomainRedirect';
|
|
|
|
|
2016-04-29 05:25:37 +00:00
|
|
|
const koa = new Koa();
|
|
|
|
const router = new Router();
|
|
|
|
|
|
|
|
// // error handler
|
|
|
|
// koa.use(async (ctx, next) => {
|
|
|
|
// try {
|
|
|
|
// await next();
|
|
|
|
// } catch (err) {
|
|
|
|
// ctx.status = err.status || 500;
|
|
|
|
// ctx.body = err.message;
|
|
|
|
// }
|
|
|
|
// });
|
|
|
|
|
2016-08-19 15:11:21 +00:00
|
|
|
router.get('/service-worker.js', async (ctx) => {
|
|
|
|
ctx.set('Content-Type', 'application/javascript');
|
|
|
|
if (process.env.NODE_ENV === 'production') ctx.set('Cache-Control', `max-age=${30}`);
|
|
|
|
await sendfile(ctx, path.join(__dirname, './static/service-worker.js'));
|
|
|
|
if (!ctx.status) ctx.throw(httpErrors.NotFound());
|
|
|
|
});
|
2016-05-07 16:18:20 +00:00
|
|
|
|
2016-08-19 15:11:21 +00:00
|
|
|
if (process.env.NODE_ENV === 'production') {
|
2016-05-07 16:18:20 +00:00
|
|
|
router.get('/static/*', async (ctx) => {
|
2016-06-01 23:48:35 +00:00
|
|
|
ctx.set({
|
2016-06-06 04:39:09 +00:00
|
|
|
'Cache-Control': `max-age=${356*24*60*60}`,
|
2016-06-01 23:48:35 +00:00
|
|
|
});
|
|
|
|
|
2016-05-07 16:18:20 +00:00
|
|
|
const stats = await sendfile(ctx, path.join(__dirname, '../dist/', ctx.path.substring(8)));
|
|
|
|
});
|
2016-04-29 05:25:37 +00:00
|
|
|
|
2016-05-24 05:55:42 +00:00
|
|
|
router.get('*', async (ctx) => {
|
|
|
|
const stats = await sendfile(ctx, path.join(__dirname, '../dist/index.html'));
|
|
|
|
if (!ctx.status) ctx.throw(httpErrors.NotFound());
|
|
|
|
});
|
2016-05-27 07:06:36 +00:00
|
|
|
|
|
|
|
koa.use(subdomainRedirect());
|
2016-05-24 05:55:42 +00:00
|
|
|
} else {
|
|
|
|
router.get('*', async (ctx) => {
|
|
|
|
const stats = await sendfile(ctx, path.join(__dirname, './static/dev.html'));
|
|
|
|
if (!ctx.status) ctx.throw(httpErrors.NotFound());
|
|
|
|
});
|
|
|
|
}
|
2016-04-29 05:25:37 +00:00
|
|
|
|
|
|
|
koa.use(router.routes());
|
|
|
|
|
|
|
|
// 404 handler
|
|
|
|
koa.use(async () => {
|
|
|
|
throw httpErrors.NotFound();
|
|
|
|
});
|
|
|
|
|
2016-06-01 23:48:35 +00:00
|
|
|
export default koa;
|