-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
85 lines (78 loc) · 2.43 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
79
80
81
82
83
84
85
/* eslint-disable indent */
const config = require("./config");
const BaseClass = require("./base/base_class");
class Main extends BaseClass {
constructor() {
super(...arguments);
}
async init() {
await config.init();
}
async start() {
const Koa = require("koa");
/**
* init app
*/
const app = new Koa();
/**
* load configs
*/
await this.init();
let { configs } = config;
this.logger.info(`init config success|configs:${Object.keys(configs).join(",")}`);
/**
* load common middleware
*/
const json = require("koa-json");
const bodyParser = require("koa-bodyparser");
app.use(bodyParser());
app.use(json());
/**
* load middleware and router
*/
const authMid = require("./middleware/auth_mid");
const router = require("./router");
const cors = require("koa2-cors");
app.use(cors());
app.use(authMid);
app.use(router.routes());
/**
* Get port from config and start
*/
const http = require("http");
this.server = http.createServer(app.callback());
this.port = configs["app_config"].port;
this.server.listen(this.port);
/**
* Event listener for HTTP server "error" event.
*/
this.server.on("error", (error) => {
if (error.syscall !== "listen") {
throw error;
}
let bind = typeof this.port === "string" ? "Pipe " + this.port : "Port " + this.port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
this.logger.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
this.logger.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
});
/**
* Event listener for HTTP server "listening" event.
*/
this.server.on("listening", () => {
let addr = this.server.address();
this.logger.info(`server listen on ${addr.address}:${addr.port}`);
});
}
}
const app = new Main();
app.start();