Controller.js 1.97 KB
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;