-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.js
54 lines (48 loc) · 1.29 KB
/
actions.js
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
Actions = {
workPool: [],
actions_: {},
regexes_: [],
register: function(path, handler) {
if (typeof path === "string") {
this.actions_[path] = handler;
} else if (path instanceof RegExp) {
this.regexes_.push({path: path, handler: handler});
} else {
throw new Error("Unrecognized path type: " + path.constructor);
}
},
onRequestStart: function(req, res) {
if (req.url in this.actions_) {
var handler = new this.actions_[req.url](req, res);
handler.onRequestStart();
} else if (this.testRegex_(req, res)) {
// pass
} else {
res.writeHead(404, {'Content-type': 'text/plain'});
res.end('404');
}
},
cleanWorkPool: function(cmdId) {
var newPool = [];
for (var i = 0, len = Actions.workPool.length; i < len; ++i) {
var work = Actions.workPool[i];
if (cmdId != work.cmd.id) {
newPool.push(work);
}
}
Actions.workPool = newPool;
},
testRegex_: function(req, res) {
var n = this.regexes_.length;
for (var i = 0; i < n; ++i) {
var re = this.regexes_[i];
if (re.path.exec(req.url) != null) {
var handler = new re.handler(req, res);
handler.onRequestStart();
return true;
}
}
return false;
},
placeholder_: function() {}
};