-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
97 lines (79 loc) · 2.34 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
'use strict';
const startTime = new Date();
const Koa = require('koa');
const hbs = require('koa-hbs');
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const send = require('koa-send');
const serve = require('koa-static');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const initConfig = require('./init/config');
const initMongoose = require('./init/mongoose');
// 初始化配置
global.config = initConfig.init();
// 初始化 Mongoose
initMongoose.init().catch(err => console.error(err.stack));
const app = new Koa();
// 异常处理
app.use(async (ctx, next) => {
try {
await next();
if (!ctx.status || ctx.status === 404) {
ctx.throw(404);
}
} catch (err) {
ctx.status = parseInt(err.status) || 500;
switch (ctx.status) {
case 404:
await send(ctx, 'public/404.html'); // __dirname + ... 是无效的
break;
case 400:
break;
case 500:
default:
await send(ctx, 'public/500.html');
break;
}
}
});
// 设置调试日志
if (process.env.NODE_ENV === 'development') {
app.use(require('koa-logger')());
}
// 设置 etag
app.use(conditional());
app.use(etag({ weak: true }));
// 嘻嘻…
app.use(async (ctx, next) => {
ctx.set('X-Powered-By', 'Koa');
await next();
});
// 设置模板引擎
app.use(hbs.middleware({
viewPath: __dirname + '/views',
defaultLayout: 'layout',
partialsPath: __dirname + '/views/partials',
}));
// 静态资源
app.use(serve(__dirname + '/public'));
// Body parser
app.use(bodyParser());
// 设置路由
const index = require('./routes/index');
const users = require('./routes/users');
const api = require('./routes/api');
router.use('/', index.routes(), index.allowedMethods());
router.use('/users', users.routes(), users.allowedMethods());
router.use('/api', api.routes(), api.allowedMethods());
app.use(router.routes(), router.allowedMethods());
app.startUp = () => app.listen(global.config.system, () => {
console.log('\x1b[90mServer started up in \x1b[1;36m%d\x1b[90m ms. ' +
'Environment is \x1b[1;36m%s\x1b[90m. ' +
'Address: \x1b[1;36mhttp://%s:%s\x1b[0m',
new Date() - startTime,
process.env.NODE_ENV,
global.config.system.host,
global.config.system.port);
});
module.exports = app;