Passed
Push — master ( 4a62f7...6ccdde )
by Zhenyu
01:23
created

src/decorators/event-metrics.js   A

Complexity

Total Complexity 13
Complexity/F 1.3

Size

Lines of Code 50
Function Count 10

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 13
eloc 39
mnd 3
bc 3
fnc 10
dl 0
loc 50
rs 10
bpm 0.3
cpm 1.3
noi 0
c 0
b 0
f 0
1
import addHooks from './helpers/add-hooks';
2
import findMetrics from './utils/find-metrics';
3
import findMetricsLabels from './utils/find-metrics-labels';
4
5
/*
6
  a decorator to timing action execution time in both success/error cases
7
  and send metrics using the client attached in context
8
 */
9
const metricsTimer = ({ extralabels = () => {}, count = false } = {}) =>
10
  addHooks({
11
    bypassHook: (p, m, { metrics }) => !metrics,
12
    storageHook: (param, meta, context, action) => {
13
      const { metrics } = context;
14
      const timer = findMetrics({ action, type: 'timer', metrics });
15
      const labels = findMetricsLabels({
16
        metric: timer,
17
        source: meta,
18
        extra: extralabels(param, meta, context),
19
      });
20
      const stopTimer = timer.startTimer(labels);
21
      const countStart = () =>
22
        count
23
          ? findMetrics({ action, type: 'start', metrics }).inc(labels, 1)
24
          : undefined;
25
      const countSuccess = () =>
26
        count
27
          ? findMetrics({
28
              action,
29
              type: 'success',
30
              metrics,
31
            }).inc(labels, 1)
32
          : undefined;
33
      const countError = () =>
34
        count
35
          ? findMetrics({ action, type: 'error', metrics }).inc(labels, 1)
36
          : undefined;
37
      return { countStart, countSuccess, countError, stopTimer };
38
    },
39
    beforeHook: (p, m, c, a, { countStart }) => countStart(),
40
    afterHook: (r, p, m, c, a, { countSuccess, stopTimer }) => {
41
      stopTimer();
42
      countSuccess();
43
    },
44
    errorHook: (e, p, m, c, a, { countError, stopTimer }) => {
45
      stopTimer();
46
      countError();
47
    },
48
  });
49
50
export default metricsTimer;
51