-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
executable file
·95 lines (85 loc) · 2.56 KB
/
server.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
import * as http from 'http'
import Koa from 'koa'
import cors from 'koa2-cors'
import respond from 'koa-respond'
import bodyParser from 'koa-bodyparser'
import compress from 'koa-compress'
import jwt from 'koa-jwt'
import { scopePerRequest, loadControllers } from 'awilix-koa'
import { logger } from './logger'
import { configureContainer } from './container'
import { dbconnect } from './db'
import { env } from './env'
import { errorHandler } from '../middleware/error-handler'
/**
* Creates a new Koa application 创建应用并返回
* @return {Promise<http.Server>}
*/
export async function createServer() {
logger.debug('Creating server...')
const app = new Koa()
const container = (app.container = configureContainer())
app.keys = ['Molly']
// use cors to enable cross-domain 允许跨域
app.use(cors({
origin: function (ctx) {
if (ctx.url === '/test') {
return false;
}
return '*';
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}));
// Custom 401 handling 处理401错误
app.use(async function (ctx, next) {
return next().catch((err) => {
if (err.status === 401) {
ctx.status = 401;
let errMessage = err.originalError ?
err.originalError.message :
err.message
ctx.body = {
error: errMessage
};
ctx.set("X-Status-Reason", errMessage)
} else {
throw err;
}
});
});
//use jwt to secret 使用jwt加密
app.use(jwt({
secret: env.SECRET
}).unless({
path: [/^\/public/, "/"]
}));
app
// Top middleware is the error handler.
.use(errorHandler)
// Compress all responses.
.use(compress())
// Adds ctx.ok(), ctx.notFound(), etc..
.use(respond())
// Parses request bodies.
.use(bodyParser())
// Creates an Awilix scope per request. Check out the awilix-koa
// docs for details: https://github.com/jeffijoe/awilix-koa
.use(scopePerRequest(container))
// load routes
.use(loadControllers('../routes/*.js', { cwd: __dirname }))
//open database 开启数据库
dbconnect()
// Create http server 开启服务
const server = http.createServer(app.callback())
// Add a `close` event listener 监听应用关闭
server.on('close', () => {
// tear down database connections, etc.
logger.debug('Server closing, bye!')
})
logger.debug('Server created, ready to listen', { scope: 'startup' })
return server
}