-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
92 lines (79 loc) · 2.61 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
var clone = require('stringify-clone');
var debugId = 0
module.exports = exports = function(request, log) {
log = log || exports.log
var proto
if (request.Request) {
proto = request.Request.prototype
} else if (request.get && request.post) {
// The object returned by request.defaults() doesn't include the
// Request property, so do this horrible thing to get at it. Per
// Wikipedia, port 4 is unassigned.
var req = request('http://localhost:4').on('error', function() { })
proto = req.constructor.prototype
} else {
throw new Error(
"Pass the object returned by require('request') to this function.")
}
if (!proto._initBeforeDebug) {
proto._initBeforeDebug = proto.init
proto.init = function() {
if (!this._debugId) {
this.on('request', function(req) {
var data = {
debugId : this._debugId,
uri : this.uri.href,
method : this.method,
headers : clone(this.headers)
}
if (this.body) {
data.body = this.body.toString('utf8')
}
log('request', data, this)
}).on('response', function(res) {
if (this.callback) {
// callback specified, request will buffer the body for
// us, so wait until the complete event to do anything
} else {
// cannot get body since no callback specified
log('response', {
debugId : this._debugId,
headers : clone(res.headers),
statusCode : res.statusCode
}, this)
}
}).on('complete', function(res, body) {
if (this.callback) {
log('response', {
debugId : this._debugId,
headers : clone(res.headers),
statusCode : res.statusCode,
body : res.body
}, this)
}
}).on('redirect', function() {
var type = (this.response.statusCode == 401 ? 'auth' : 'redirect')
log(type, {
debugId : this._debugId,
statusCode : this.response.statusCode,
headers : clone(this.response.headers),
uri : this.uri.href
}, this)
})
this._debugId = ++debugId
}
return proto._initBeforeDebug.apply(this, arguments)
}
}
if (!request.stopDebugging) {
request.stopDebugging = function() {
proto.init = proto._initBeforeDebug
delete proto._initBeforeDebug
}
}
}
exports.log = function(type, data, r) {
var toLog = {}
toLog[type] = data
console.error(toLog)
}