forked from Aminadav/node-run-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (92 loc) · 1.98 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
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 as 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={}
// res=_.extend(res,require('express/lib/response'));
var headers={}
var code=200;
res.setHeader=res.set=res.header=(x,y)=>{
headers[x]=y
headers[x.toLowerCase()]=y
return res
}
// 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=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
}