-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.prod.js
99 lines (82 loc) · 2.3 KB
/
index.prod.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
98
99
const Koa = require('koa')
const Router = require('koa-router')
const glob = require('glob')
const koaStatic = require('koa-static')
const history = require('koa2-history-api-fallback')
const {PORT} = require('./config/server')
const {getRouterPath, log} = require('./utils/framework')
const app = new Koa()
const router = new Router()
process.env.NODE_ENV = 'production'
registerApp()
async function registerApp () {
app.use(async (ctx, next) => {
log.info(ctx.url)
await next()
})
try {
await registerMiddlewares();
await registerRoutes();
app.use(router.routes());
app.use(router.allowedMethods());
app.use(history({
htmlAcceptHeaders: ['text/html'],
index: '/index.html'
}));
app.use(koaStatic('vue-dist'));
app.use(koaStatic('public'));
app.listen(PORT);
log.info('Production has been started at port:', PORT);
} catch (e) {
log.error(e)
log.error('Fail to start prod env\n\n')
}
}
async function registerRoutes () {
return new Promise((resolve, reject) => {
glob('actions/**/*.js', (err, files) => {
if (err) {
log.error('Fail to read actions file')
log.error(err)
reject()
return
}
files.forEach(actionPath => {
let action = require(`./${actionPath}`)
if (typeof action.handler !== 'function') {
log.warn(actionPath, '(ignore warm) action files should includes handler and must be function type!')
return
}
if (!action.routerPath) {
action.routerPath = getRouterPath(actionPath)
}
router.get(action.routerPath, action.handler)
})
resolve()
})
})
}
async function registerMiddlewares () {
return new Promise((resolve, reject) => {
glob('middlewares/**/*.js', (err, files) => {
if (err) {
log.error('fail to read middlewares file')
log.error(err)
reject()
return
}
files.forEach(middlewarePath => {
let middleware = require(`./${middlewarePath}`)
if (typeof middleware !== 'function') {
return
}
router.use(middleware)
})
resolve()
})
})
}
process.on('unhandledRejection', error => {
console.error('unhandledRejection', error);
process.exit(1) // To exit with a 'failure' code
});