-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (58 loc) · 1.5 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
/**
* Module Dependencies
*/
var qs = require('querystring')
var debug = require('debug')
/**
* Export `superagent-trace`
*/
module.exports = trace
/**
* Initialize the `trace`
*
* @param {Superagent} superagent
* @param {Object} options
* @return {Superagent}
*/
function trace (superagent, options) {
options = options || {}
// options.logging
var log = options.log || debug('superagent:trace')
log = typeof debug === 'string' ? debug(log) : log
// options.verbose
var verbose = options.verbose === undefined ? false : options.verbose
// options.slow
var slow = options.slow || 1000
// Monkey-path end
var end = superagent.Request.prototype.end
superagent.Request.prototype.end = function (fn) {
var url = serialize(this)
var start = new Date()
verbose && log('--> %s', url)
end.call(this, function (err, res) {
var time = res && res.headers && res.headers['x-response-time']
if (err) {
time
? log('-x- %s (%s %s)', url, err.message, time)
: log('-x- %s (%s)', url, err.message)
return fn(err, res)
} else {
time
? log('<-- %s (%s %s)', url, res.status, time)
: log('<-- %s (%s)', url, res.status)
return fn(err, res)
}
})
}
return superagent
}
/**
* Serialize the request
*
* @param {Object} request
* @return {String}
*/
function serialize (request) {
var query = qs.stringify(request.qs)
return request.method + ' ' + request.url + (query ? '?' + query : '')
}