-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
80 lines (61 loc) · 1.94 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
const path = require('path');
const fs = require('fs');
const koa = require('koa');
const middleware = require('./middleware');
const component = require('./component');
const config = require('./config-default');
class Application {
constructor(appDir, settings) {
// get settings
do {
settings = settings ? settings : {};
if (!appDir) break;
const settingDir = path.join(appDir, 'config');
// new mysrv({option: value});
if (typeof appDir == 'object') {
settings = appDir;
break;
}
if (fs.existsSync(settingDir)) settings = Object.assign(require(settingDir), settings);
} while (0);
this.settings = Object.assign(config, settings);
this.settings.appDir = appDir;
this.context = {};
this.middlewares = [];
this.server = new koa();
}
/**
* start server
*/
run() {
// register system middlewares
middleware(this);
// load application components
component(this);
// sort middlewares by level
this.middlewares.sort((a ,b) => b.level - a.level);
for (let middleware of this.middlewares) {
this.use(middleware(this));
}
this.server.listen(this.settings.port);
setImmediate(() => {
console.log(`listening on ${this.settings.port}`);
});
}
/**
* add middleware
*/
use(middleware) {
this.server.use(middleware);
}
/**
* register middleware
* middleware.level 表示中间件的优先级
* level 越大,优先级越高,优先执行。默认为 10
*/
registerMiddleware(middleware) {
if (!middleware.level) middleware.level = 10;
this.middlewares.push(middleware);
}
}
module.exports = Application;