-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
68 lines (59 loc) · 1.59 KB
/
app.js
File metadata and controls
68 lines (59 loc) · 1.59 KB
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
// 工具
const path = require('path')
const { MESSAGE, STATUS } = require('./utils/message')
// 配置
const config = require('./config')
const Koa = require('koa')
const app = new Koa()
// 引入中间件
const Router = require('koa-router')
const logger = require('koa-logger')
const asset = require('koa-static2')
const bodyParser = require('koa-bodyparser')
// 使用bodyParser
app.use(bodyParser())
// 引入mongoDB
const db = require('./db')
// 链接数据库
db.connect().then(() => {
if (process.env.NODE_ENV !== 'test') {
console.log(MESSAGE.dbSuccess)
}
}).catch(() => {
if (process.env.NODE_ENV !== 'test') {
console.log(MESSAGE.dbFailed)
}
db.disconnect()
})
const router = new Router()
// 引入路由
const cardRoutes = require('./routes/card')
const enumRoutes = require('./routes/enum')
// 使用日志中间件, 测试环境不使用日志中间件
if (process.env.NODE_ENV !== 'test') {
app.use(logger())
}
// 使用静态资源访问中间件
app.use(asset('/public', path.join(__dirname, config.static)))
// 错误处理中间件
app.use(async (ctx, next) => {
try {
ctx.error = (code, message) => {
ctx.throw(code || STATUS.error, message || MESSAGE.error)
}
await next()
} catch (e) {
let status = e.status || STATUS.error
let message = e.message || MESSAGE.error
ctx.body = {
status,
message
}
}
})
// 加载路由
router.use('/card', cardRoutes.routes(), cardRoutes.allowedMethods())
router.use('/enum', enumRoutes.routes(), enumRoutes.allowedMethods())
app.use(router.routes())
// 导出Koa app
module.exports = app