-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
78 lines (69 loc) · 1.79 KB
/
index.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
import Koa from 'koa';
import koaBody from 'koa-body';
import cors from '@koa/cors';
import koaViews from 'koa-views';
import * as path from 'path';
import resMsg from './lib/response';
import auth from './lib/auth';
import * as routes from './routes';
import {sysCfg, serverCfg, redisCfg} from './config';
import staticFiles from './lib/static-files';
import Redis from './lib/redis';
import {ScheduleJob} from './lib/schedule';
const app = new Koa();
// ctx.redis
app.context.redis = redisCfg.reduce((s, v) => {
s[v.key] = new Redis(v.opts);
return s;
},
{});
// ctx.send
app.use(resMsg());
// cors
app.use(cors({
origin: '*',
credentials: true,
}));
// 生产环境静态文件放在nginx下
if (sysCfg.nodeEnv !== 'production') {
app.use(staticFiles(`${sysCfg.prefix}/static/`, `${__dirname}/static`));
app.use(koaViews(path.join(__dirname, 'static/'), {extension: 'html'}));
}
// body parser
app.use(koaBody({
multipart: true,
formidable: {
maxFileSize: 20 * 1024 * 1024,
},
}));
// 校验token
app.use(auth({
filter: [
'\\.(js|css|jpg|ico)$',
`^${sysCfg.prefix}${sysCfg.apiPrefix}/login$`,
`^${sysCfg.prefix}${sysCfg.apiPrefix}/register$`,
`^${sysCfg.prefix}/login$`,
`^${sysCfg.prefix}/register$`,
`^${sysCfg.prefix}$`,
],
}));
// routes
Object.keys(routes)
.forEach((k) => {
app.use(routes[k].routes())
.use(routes[k].allowedMethods());
});
// error handler
app.on('error', async (err, ctx) => {
ctx.status = 500;
serverCfg.log.error('×××××× System error:', err.stack);
});
// listening
const port = Number(sysCfg.port);
app.listen(port, '0.0.0.0')
.on('listening', () => {
serverCfg.log.info(`Listening on port: ${port}`);
serverCfg.log.info(`Api Prefix: ${sysCfg.prefix}`);
});
// schedule
ScheduleJob.getInstance(app.context);