-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
97 lines (80 loc) · 1.78 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
/**
* Module Dependencies
*/
var Hook = require('koa-middleware-hook')
var Debug = require('debug')
var chalk = require('chalk')
var ms = require('ms')
/**
* Export `Timer`
*/
module.exports = Timer
/**
* Colors
*/
var log_medium = chalk.yellow
var log_fast = chalk.green
var log_slow = chalk.red
/**
* Export `Timer`
*
* @param {Object} options
* @return {Function}
*/
function Timer (options) {
// setup the hooks
var hook = Hook(marker, reducer(options))
return function timer (generator) {
return hook(generator)
}
}
/**
* Marker
*
* @return {Date}
*/
function marker () {
return new Date()
}
/**
* Reduce
*
* @param {String} name
* @param {Date} top_start
* @param {Date} top_end
* @param {Date} bottom_start
* @param {Date} bottom_end
*/
function reducer (options) {
options = options || {}
var debug = Debug(options.debug || 'koa:timer')
var threshold = options.threshold || false
var verbose = options.verbose || false
var duration = speed(ms(options.slow) || 75)
return function _reducer (name, top_start, top_end, bottom_start, bottom_end) {
var top = top_end - top_start
var bottom = null
if (bottom_start && bottom_end) {
bottom = bottom_end - bottom_start
}
if (!threshold || threshold < top + bottom) {
if (verbose) {
bottom !== null
? debug('%s: ↓%s | ↑%s', name || 'mw', duration(top), duration(bottom))
: debug('%s: ⇵ %s', name || 'mw', duration(top))
} else {
debug('%s: ⇵ %s', name || 'mw', duration(top + bottom))
}
}
}
}
function speed (slow) {
var medium = slow / 2
return function (actual) {
return actual > slow
? log_slow(ms(actual))
: actual > medium
? log_medium(ms(actual))
: log_fast(ms(actual))
}
}