-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
71 lines (62 loc) · 1.84 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
'use strict'
const Koa = require('koa')
const path = require('path')
const validate = require('koa-validate')
const koaBody = require('koa-body')
const config = require('config')
const koaJwt = require('koa-jwt')
const pathToRegexp = require('path-to-regexp')
const staticCache = require('koa-static-cache')
const routerConfig = require('./router-config')
const Router = require('koa-router')
const middleware = require('./middlewares')
const app = module.exports = new Koa()
const router = new Router()
const resolve = file => path.resolve(__dirname, file)
const isProd = process.env.NODE_ENV === 'production'
const jwtSecret = config.get('jwt.secret')
validate(app)
app
.use(serve('/dist', './dist'))
.use(serve('/public', './public'))
.use(middleware.util)
.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
.use(koaJwt({ secret: jwtSecret }).unless((ctx) => {
if (/^\/api/.test(ctx.path)) {
return pathToRegexp([
'/api/github/login',
'/api/github/callback',
'/api/articles',
'/api/articles/:id',
'/api/login',
'/api/register',
'/api/wallpaper'
]).test(ctx.path)
}
return true
}))
.use(koaBody({ multipart: true }))
.use(routerConfig.api.routes())
.use(routerConfig.api.allowedMethods())
app.proxy = config.get('proxy')
/* istanbul ignore if */
if (!module.parent) {
const port = config.get('port')
const host = config.get('host')
app.use(require('./middlewares/view').render(app))
app.listen(port, host)
console.log(`server started at http://${host}:${port}`)
}
function serve (prefix, filePath) {
return staticCache(path.resolve(__dirname, filePath), {
prefix: prefix,
gzip: true,
dynamic: true,
maxAge: 60 * 60 * 24 * 30
})
}