-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
120 lines (114 loc) · 2.66 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var _ = require("lodash");
var request = require("express/lib/request");
module.exports = function(app) {
app.use((req, res, next) => {
req.runMiddleware = (path, options, callback) => {
if (_.isFunction(options)) {
callback = options;
options = {};
}
options.original_req = req;
options.original_res = res;
app.runMiddleware(path, options, callback);
};
next();
});
if (app.runMiddleware) return; // Do not able to add us twice
app.runMiddleware = function(path, options, callback) {
if (callback) callback = _.once(callback);
if (typeof options == "function") {
callback = options;
options = null;
}
options = options || {};
options.url = path;
var new_req, new_res;
if (options.original_req) {
new_req = options.original_req;
for (var i in options) {
if (i == "original_req") continue;
new_req[i] = options[i];
}
} else {
new_req = createReq(path, options);
}
new_res = createRes(callback);
app(new_req, new_res);
};
/* end - APP.runMiddleware*/
};
function createReq(path, options) {
if (!options) options = {};
var req = _.extend(
{
method: "GET",
host: "",
cookies: {},
query: {},
url: path,
headers: {},
},
options
);
req.method = req.method.toUpperCase();
// req.connection=_req.connection
return req;
}
function createRes(callback) {
var res = {
_removedHeader: {},
_statusCode: 200,
statusMessage: 'OK',
get statusCode() {
return this._statusCode
},
set statusCode(status) {
this._statusCode = status
this.status(status)
}
};
// res=_.extend(res,require('express/lib/response'));
var headers = {};
var code = 200;
res.set = res.header = (x, y) => {
if (arguments.length === 2) {
res.setHeader(x, y);
} else {
for (var key in x) {
res.setHeader(key, x[key]);
}
}
return res;
}
res.setHeader = (x, y) => {
headers[x] = y;
headers[x.toLowerCase()] = y;
return res;
};
res.getHeader = (x) => headers[x];
// res.get=(x) => {
// return headers[x]
// }
res.redirect = function(_code, url) {
if (!_.isNumber(_code)) {
code = 301;
url = _code;
} else {
code = _code;
}
res.setHeader("Location", url);
res.end();
// callback(code,url)
};
res.status = res.sendStatus = function(number) {
code = number;
return res;
};
res.end = res.send = res.write = function(data) {
if (callback) callback(code, data, headers);
// else if (!options.quiet){
// _res.send(data)
// }
};
return res;
}