This repository has been archived by the owner on Feb 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (89 loc) · 2.23 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var http = require("http");
var Layer = require("lib/layer");
var makeRoute = require("lib/route");
var methods = require("methods");
module.exports = express = function() {
var app = function(req, res, next) {
app.monkey_patch(req, res);
app.handle(req, res, next);
}
app.listen = function(port, callback) {
return http.createServer(this).listen(port, callback);
}
app.stack = [];
app.handle = function(req, res, out) {
var index = 0,
stack = this.stack,
originalUrl = null;
function next(err) {
var layer = stack[index++];
if (originalUrl != null) {
req.url = originalUrl;
originalUrl = null;
}
if (!layer) {
if (out) {
return out(err);
} else {
res.statusCode = err ? 500 : 404;
res.end();
}
} else {
req.app = app;
try {
var match = layer.match(req.url);
if (match === undefined) return next(err);
req.params = match.params;
if (layer.handle.handle) {
originalUrl = req.url;
req.url = req.url.substr(layer.path.length);
}
var arity = layer.handle.length;
if (err) {
if (arity === 4) {
layer.handle(err, req, res, next);
} else {
next(err);
}
} else if (arity < 4) {
layer.handle(req, res, next);
} else {
next();
}
} catch (e) {
next(e);
}
}
}
next();
}
app.use = function(path, m, end) {
if (typeof path == "function") {
m = path;
path = "/";
};
var layer = new Layer(path, m, end);
this.stack.push(layer);
}
app.route = function(path) {
var rt = makeRoute();
app.use(path, rt, true);
return rt;
}
methods.concat("all").forEach(function(method) {
app[method] = function(path, m) {
var route = app.route(path);
route.use(method, m);
return app;
}
})
app.monkey_patch = function(req, res) {
var reqP = require("lib/request");
var resP = require("lib/response");
req.__proto__ = reqP;
res.__proto__ = resP;
req.res = res;
res.req = req;
}
return app;
}