-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·60 lines (48 loc) · 1.13 KB
/
index.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
55
56
57
58
59
60
function slice(arr) {
return Array.prototype.slice.call(arr);
}
var stackr = module.exports = function() {
var core = stackr.substack.apply(stackr, arguments);
function entry(req, res) {
core(req, res, function(err) {
entry.handleError(req, res, err);
});
}
entry.use = core.use;
entry.handleError = stackr.handleError;
return entry;
};
stackr.substack = function() {
var middleware = [];
function entry(req, res, done) {
var i = 0, len = middleware.length;
function next(err) {
try {
if(err) return done(err);
middleware[i++](req, res, i < len ? next : done);
} catch(e) {
done(e);
}
}
if(len)
next();
else
done();
}
entry.use = function(first) {
middleware = middleware.concat(first instanceof Array ? first : slice(arguments));
return this;
};
entry.use.apply(entry, arguments);
return entry;
};
stackr.handleError = function(req, res, err) {
if(err) {
console.error(err.stackr || err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end((err.stackr || err) + '\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found\n');
}
};