Controller.js
1.97 KB
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
96
97
98
99
100
var path=require('path');
var util = require('util');
var md5 = require('md5');
var Emitter=require('events');
/*重写控制器*/
var toString= Object.prototype.toString;
var Controller=function(interfaces){
this.interfaces=interfaces;
this.routers=[];
Emitter.call(this);
};
util.inherits(Controller,Emitter);
/*解析 req 规则*/
Controller.prototype.__parseReq=function(req){
return{
defRes:req.xhr?"json":"render"
}
}
Controller.prototype.__define=function(method,router,view,apis,callback){
var me=this;
/*参数验证*/
var guid=md5(router+":"+method)
me.on(guid,function(){
var args=[].slice.call(arguments, 0);
var req=args[0],res=args[1];
/*如果接口不存在 就实现express 原来的方法*/
if(!apis.length){
if(callback){
callback.apply({},args);
}else{
res.render(view);
}
return;
}
args.push(function(err,interfaces,names){
//callback
var model={};
if(typeof callback=="function"){
model=callback.apply({},interfaces.concat(args));
}else{
interfaces.forEach(function(item,index){
model[names[index]]=item;
});
}
if(model){
if(view&&method=="get"&&!req.xhr){
res.render(view,model);
}else{
res.json(model);
}
}
});
//调用接口获取数据
me.interfaces.require.apply(me.interfaces,[apis].concat(args));
});
me.routers.push({
guid:guid,
url:router,
method:method
});
}
Controller.prototype.get=function(router,views,apis,callback){
var me=this;
if(toString.call(views)=='[object Array]'){
callback=apis;
apis=views;
views=null;
}else if(typeof views =='function'){
callback=views;
apis=[];
views=null;
}
if(typeof apis=="function"){
callback=apis;
apis=[];
}
apis=apis||[];
me.__define("get",router,views,apis,callback);
}
Controller.prototype.post=function(router,apis,callback){
var me=this;
if(typeof apis=="function"){
callback=apis;
apis=[];
}
me.__define("post",router,null,apis,callback);
}
module.exports= Controller;