-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (48 loc) · 1.31 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
'use strict'
const EventEmitter = require('events').EventEmitter
const singleMetric = require('@telemetry-js/metric').single
exports.sync = function (name, metricOptions, fn) {
if (typeof metricOptions === 'function') {
fn = metricOptions
metricOptions = {}
}
return function plugin () {
return new FunctionCollector(false, name, fn, metricOptions)
}
}
exports.async = function (name, metricOptions, fn) {
if (typeof metricOptions === 'function') {
fn = metricOptions
metricOptions = {}
}
return function plugin () {
return new FunctionCollector(true, name, fn, metricOptions)
}
}
class FunctionCollector extends EventEmitter {
constructor (async, name, fn, metricOptions) {
super()
this._async = async
this._name = name
this._fn = fn
this._metricOptions = metricOptions
}
ping (callback) {
// TODO: reuse metric objects between pings
const metric = singleMetric(this._name, this._metricOptions)
if (this._async) {
this._fn((err, value) => {
if (err) return callback(err)
metric.record(value)
this.emit('metric', metric)
callback()
})
} else {
const value = this._fn()
metric.record(value)
this.emit('metric', metric)
// No need to dezalgo ping()
callback()
}
}
}