1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-01 00:08:27 +01:00
unleash.unleash/lib/client-metrics/service.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2016-10-27 16:55:38 +02:00
'use strict';
2016-10-27 20:51:39 +02:00
2016-11-02 12:49:25 +01:00
const { EventEmitter } = require('events');
2016-10-27 16:55:38 +02:00
2016-11-04 16:17:11 +01:00
module.exports = class UnleashClientMetrics extends EventEmitter {
constructor (metricsDb, interval = 10000) {
2016-11-02 12:49:25 +01:00
super();
this.interval = interval;
2016-11-04 16:17:11 +01:00
this.db = metricsDb;
2016-10-27 16:55:38 +02:00
this.highestIdSeen = 0;
2016-11-04 22:14:58 +01:00
this.db.getMetricsLastHour().then(metrics => {
2016-11-04 16:17:11 +01:00
this.addMetrics(metrics);
this.startPoller();
this.emit('ready');
2016-11-04 16:17:11 +01:00
});
this.timer = null;
2016-10-27 16:55:38 +02:00
}
addMetrics (metrics) {
2016-11-04 16:17:11 +01:00
if (metrics && metrics.length > 0) {
this.highestIdSeen = metrics[metrics.length - 1].id;
2016-10-27 20:51:39 +02:00
}
2016-11-02 12:49:25 +01:00
this.emit('metrics', metrics);
2016-10-27 16:55:38 +02:00
}
2016-11-04 16:17:11 +01:00
startPoller () {
this.timer = setInterval(() => {
2016-11-04 16:17:11 +01:00
this.db.getNewMetrics(this.highestIdSeen)
.then(metrics => this.addMetrics(metrics));
}, this.interval);
this.timer.unref();
2016-10-27 16:55:38 +02:00
}
insert (metrics) {
2016-11-04 16:17:11 +01:00
return this.db.insert(metrics);
2016-10-27 16:55:38 +02:00
}
destroy () {
try {
clearTimeout(this.timer);
} catch (e) {}
}
2016-10-27 16:55:38 +02:00
};