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

var Match = require("./Match.js");

var Filter=function(interfaces,controllers){
	this.rules=[];
	this.interfaces=interfaces;
	this.controllers=controllers;
	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 == "string") {
        apis = [apis];
    }
	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){
            return callback.apply({},args);
		}
        var fn = function (err, interfaces, names) {
            callback.apply({}, interfaces.concat(args));
        };
		me.interfaces.require.apply(me.interfaces,[apis, req, res, fn]);
	});
};
Filter.prototype.rules = function (rules) { 

};
Filter.prototype.use=function(router,method){
    var me = this, rules = [], func = [];
    rules = me.rules.filter(function (rule, index){
        if (typeof rule.method == "string") {
            rule.method = [rule.method];
        }
		return Match(rule.router,router)
		&& !(rule.method.indexOf(method) == -1);
    });
	rules.forEach(function(rule){
        func.push(function (req, res, next){
			me.emit(rule.guid,req,res,next);
		});
	});
	return func;
}




module.exports= Filter;