Filter.js 1.17 KB
var path=require('path');
var util = require('util');
var md5 = require('md5');
var Emitter=require('events');

var Filter=function(interfaces){
	this.rules=[];
	this.interfaces=interfaces;
	Emitter.call(this);
};
util.inherits(Filter,Emitter);

Filter.prototype.define = function(router,method,apis,callback) {
	var me=this,guid=md5(router+":"+method);

	if(typeof apis=="function"){
		callback=apis;
		apis=[];
	}

	me.rules.push({
		guid:guid,
		router:router,
		method:method
	});

	me.on(guid,function(){
		var args=[].slice.call(arguments, 0);
		var req=args[0],res=args[1];
		if(!apis.length){
			callback.apply({},args);
			return;
		}
		args.push(function(err,interfaces,names){
			callback.apply({},interfaces.concat(args));
		});

		me.interfaces.require.apply(me.interfaces,[apis].concat(args));
	});
};

Filter.prototype.use=function(router,method){
	var me=this,rules=[],func=[];
	rules=me.rules.filter(function(rule,index){
		return new RegExp(rule.router,'g').test(router)
		&&new RegExp(rule.method,'ig').test(method);
	});
	rules.forEach(function(rule){
		func.push(function(req,res,next){
			me.emit(rule.guid,req,res,next);
		});
	});
	return func;
}




module.exports= Filter;