-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (62 loc) · 1.37 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
/**
* time cost
*/
const uuid = require('uuid');
const times = {};
const names = [];
function init(ctx) {
if (!ctx.koatcid) {
let id = uuid.v4();
Object.defineProperty(ctx, 'koatcid', {
value: id,
writable: false
});
return times[id] = {
prev: 0,
list: [],
diff: [],
};
}
return times[ctx.koatcid];
}
function intro(ctx) {
let time = init(ctx);
time.list.push(+new Date);
}
function outer(ctx, callback) {
let time = init(ctx);
let start = time.list.pop();
let diff = +new Date - start - time.prev;
time.prev += diff;
time.diff.unshift(diff);
if (time.list.length === 0 && typeof callback === 'function') {
let data = {};
time.diff.forEach((diff, idx) => {
data[names[idx]] = diff;
});
delete times[ctx.koatcid];
callback(data);
}
}
function wrap(fn, callback) {
let temp = async (ctx, next) => {
intro(ctx);
await fn(ctx, next);
outer(ctx, callback);
}
return temp;
}
module.exports = function(app, callback) {
let middlewares = app.middleware;
if (!middlewares.length) {
const app_use = app.use;
app.use = function(fn, name) {
name = name || fn.name || fn._name || ('index_' + names.length);
names.push(name);
return app_use.call(this, wrap(fn, callback));
};
} else {
throw new Error('koa-tc init need before use');
}
return app;
}