forked from huanglong-zz/easy-mock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
76 lines (68 loc) · 2.12 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
'use strict'
const _ = require('lodash')
const koa = require('koa')
const path = require('path')
const cors = require('koa-cors')
const config = require('config')
const error = require('koa-error')
const favicon = require('koa-favicon')
const validate = require('koa-validate')
const jwtMongo = require('koa-jwt-mongo')
const bodyParser = require('koa-bodyparser')
const pathToRegexp = require('path-to-regexp')
const staticCache = require('koa-static-cache')
const koaBunyanLogger = require('koa-bunyan-logger')
const logger = require('./util/log')
const middleware = require('./middlewares')
const routerConfig = require('./router-config')
const app = module.exports = koa()
const resolve = file => path.resolve(__dirname, file)
const isProd = process.env.NODE_ENV === 'production'
const serve = (pf, filePath, cache) => staticCache(resolve(filePath), {
prefix: pf,
gzip: true,
maxAge: cache && isProd ? 60 * 60 * 24 * 30 : 0
})
validate(app)
const requestLogger = isProd
? koaBunyanLogger.requestLogger()
: function * (next) {
yield next
}
app
.use(favicon(path.join(__dirname, '/public/images/icon.png')))
.use(serve('/dist', './dist'))
.use(serve('/public', './public'))
.use(koaBunyanLogger(logger))
.use(koaBunyanLogger.requestIdContext())
.use(requestLogger)
.use(cors())
.use(error())
.use(bodyParser())
.use(middleware.common)
.use(middleware.error)
.use(jwtMongo({
uri: config.get('db'),
jwtExp: config.get('jwt.expire'),
collection: config.get('jwt.collection'),
jwtOptions: {
secret: config.get('jwt.key'),
key: config.get('jwt.key')
},
jwtUnless () {
const path = this.path
const prefix = `/${path.split('/')[1]}`
return !(new RegExp(config.get('routerPrefix.api'))).test(prefix)
? true : _.some(config.get('publicAPIs').map(
o => pathToRegexp(o).test(this.path)
), Boolean)
}
}))
.use(routerConfig.mock.routes())
.use(routerConfig.mock.allowedMethods())
.use(routerConfig.api.routes())
.use(routerConfig.api.allowedMethods())
.use(middleware.view(app))
if (!module.parent) {
app.listen(config.get('port'))
}