-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (83 loc) · 2.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import path from 'path';
import Koa from 'koa';
import serve from 'koa-static';
import views from 'koa-views';
import logger from 'koa-logger';
import conditional from 'koa-conditional-get';
import etag from 'koa-etag';
import error from 'koa-error';
import bodyParser from 'koa-bodyparser';
import methodOverride from 'koa-methodoverride';
import send from 'koa-send';
import mount from 'koa-mount';
import convert from 'koa-convert';
import helmet from 'koa-helmet';
const router = require('koa-router')();
const app = new Koa();
app
.use(helmet())
.use(bodyParser())
.use(methodOverride())
.use(logger())
.use(convert(conditional()))
.use(convert(etag()))
.use(convert(error()))
.use(convert(serve(path.join(__dirname, 'public'))))
.use(mount('/jspm_packages', convert(serve(path.join(__dirname, 'jspm_packages')))));
// use Jade templates
app.use(convert(views(path.join(__dirname, 'server/views'), {
extension: 'jade'
})));
// serve jspm configuration file
app.use(async function handleJspmConfig(ctx, next) {
ctx.path === '/config.js'
? await send(ctx, 'jspm.config.js', { root: __dirname })
: await next();
});
// index route
router.get('/', convert(function* renderIndexPage() {
yield this.render('index');
}));
// use router
app
.use(router.routes())
.use(router.allowedMethods());
// 404 error handler
app.use(async function handleNotFoundError(ctx, next) {
if (ctx.status !== 404) await next();
// we need to explicitly set 404 here
// so that koa doesn't assign 200 on body
ctx.status = 404;
switch (ctx.accepts('html', 'json')) {
case 'html':
ctx.type = 'html';
ctx.body = '<p>Not Found</p>';
break;
case 'json':
ctx.body = {
message: 'Not Found'
};
break;
default:
ctx.type = 'text';
ctx.body = 'Not Found';
}
});
// common errors handler
app.use(async function handleCommonError(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.type = 'html';
ctx.body = '<p>Something gone really wrong.</p>';
ctx.app.emit('error', err, ctx);
}
});
app.use(async function throwError() {
throw new Error();
});
/* eslint no-console: 0 */
app.on('error', err => console.log(err));
app.listen(process.env.PORT || (process.env.NODE_ENV === 'production' ? 80 : 3000));
export { app, router };