UNPKG

1.75 kBJavaScriptView Raw
1var koa = require('koa');
2var router = require('koa-router')
3var merge = require('merge-descriptors');
4var session = require('koa-session');
5var koa_body = require('koa-body');
6
7
8
9module.exports = Server;
10Server.prototype.__proto__ = new koa()/*继承koa*/
11function Server (options,app){
12 this.port = options.port;
13 this.app = app
14 this.serverStartupMiddleware()/*添加默认系统级别的中间件*/
15
16}
17
18
19
20
21Server.prototype.loader = function(app){
22 var Application = require('./application');
23 if(!(app instanceof Application)){
24 console.error('请传入alajs() 产生的对象');
25 throw new Error();
26 }
27 app.server = this; /*给app指定server对象,必须在加载前,因为加载过程中,会使用server对象来产生路由*/
28 /*!!!!!!!!!!!!!!!!!!!!!!*/
29 this.setMiddleware()/*加载之前,必须设置路由中间件,不然action无法自动路由*/
30
31 app.load();/*加载模块资源,自动定义控制器,action,*/
32
33}
34
35
36
37Server.prototype.setMiddleware = function(){
38
39 this.use(router(this))
40
41}
42
43Server.prototype.serverStartupMiddleware = function(){
44 this.keys = [this.app.name];/*设置session key 为app名称*/
45
46
47 this.use(koa_body());/*添加post body处理中间件*/
48 this.use(function *(next) {
49 this.post = this.request.body;
50 yield next;
51 });
52
53 this.use(session());/*使用session*/
54 this.extendFromContext();/*扩展context*/
55}
56
57
58/*继承middle中的this对象*/
59Server.prototype.extendFromContext = function(){
60 var app = this.app;
61 var contextEditer = require('./context')
62 this.use(function *(next){
63 contextEditer(this,app);
64 yield next
65 })
66}
67
68
69/*启动服务器,启动之前,还能设置中间件,名为路由后中间件*/
70Server.prototype.bootstrap = function(){
71 this.listen(this.port);
72}
73
74
75