-
Notifications
You must be signed in to change notification settings - Fork 27
/
app.js
77 lines (65 loc) · 1.87 KB
/
app.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
require('dotenv-flow').config()
const path = require('node:path')
const process = require('node:process')
const Koa = require('koa')
const koaLogger = require('koa-logger')
const bodyparser = require('koa-body')
const staticServe = require('koa-static')
const session = require('koa-session')
const send = require('koa-send')
// In order to apply the moongoose plugin,
// DB must be inited before others.
require('./config/db')
const config = require('./config')
const router = require('./routes')
const logger = require('./utils/logger')
const setup = require('./config/setup')
const app = new Koa()
// 日志,会在控制台显示请求的方法和路由
if (process.env.NODE_ENV !== 'test') {
app.use(koaLogger())
}
app.keys = [ config.secretKey ]
app.use(session({
key: 'koa:oj:sess',
maxAge: 7 * 24 * 60 * 60 * 60 * 1000, // ms
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
}, app))
app.use(bodyparser({
formidable: {
uploadDir: path.resolve(__dirname, 'public/uploads'),
},
multipart: true,
urlencoded: true,
}))
app.use(staticServe(path.join(__dirname, 'public'), {
gzip: true,
maxage: 7 * 24 * 60 * 60, // 7 天不更新,也就是缓存期限
}))
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.status || 500
ctx.body = {
error: err.message,
}
logger.error(`${err.status} -- ${err.message}\n${err.stack}`)
}
})
app.use(async (ctx, next) => {
await next()
if (ctx.status === 404) {
return send(ctx, 'public/index.html')
}
})
app.use(router.routes()).use(router.allowedMethods())
// do not start on 'test'
if (process.env.NODE_ENV !== 'test') {
app.listen(config.port, async () => {
await setup()
logger.info(`The server is running at http://localhost:${config.port}`)
})
}
module.exports = app