Filter.js
1.17 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
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;