mirror of
				https://github.com/Unleash/unleash.git
				synced 2025-10-27 11:02:16 +01:00 
			
		
		
		
	Instead of instructing users to do static calls in to Unleash, she should instead be allwed to specify the log provider as an option to Unleash. This commit introduces the "getLogger" option, a function responsible for creating a logger.
		
			
				
	
	
		
			61 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			61 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
'use strict';
 | 
						|
 | 
						|
const { EventEmitter } = require('events');
 | 
						|
 | 
						|
const TEN_SECONDS = 10 * 1000;
 | 
						|
 | 
						|
class ClientMetricsStore extends EventEmitter {
 | 
						|
    constructor(metricsDb, getLogger, pollInterval = TEN_SECONDS) {
 | 
						|
        super();
 | 
						|
        this.logger = getLogger('client-metrics-store.js');
 | 
						|
        this.metricsDb = metricsDb;
 | 
						|
        this.highestIdSeen = 0;
 | 
						|
 | 
						|
        this._init(pollInterval);
 | 
						|
    }
 | 
						|
 | 
						|
    async _init(pollInterval) {
 | 
						|
        try {
 | 
						|
            const metrics = await this.metricsDb.getMetricsLastHour();
 | 
						|
            this._emitMetrics(metrics);
 | 
						|
        } catch (err) {
 | 
						|
            this.logger.error('Error fetching metrics last hour', err);
 | 
						|
        }
 | 
						|
        this._startPoller(pollInterval);
 | 
						|
        this.emit('ready');
 | 
						|
    }
 | 
						|
 | 
						|
    _startPoller(pollInterval) {
 | 
						|
        this.timer = setInterval(() => this._fetchNewAndEmit(), pollInterval);
 | 
						|
        this.timer.unref();
 | 
						|
    }
 | 
						|
 | 
						|
    _fetchNewAndEmit() {
 | 
						|
        this.metricsDb
 | 
						|
            .getNewMetrics(this.highestIdSeen)
 | 
						|
            .then(metrics => this._emitMetrics(metrics));
 | 
						|
    }
 | 
						|
 | 
						|
    _emitMetrics(metrics) {
 | 
						|
        if (metrics && metrics.length > 0) {
 | 
						|
            this.highestIdSeen = metrics[metrics.length - 1].id;
 | 
						|
            metrics.forEach(m => this.emit('metrics', m.metrics));
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
    // Insert new client metrics
 | 
						|
    insert(metrics) {
 | 
						|
        return this.metricsDb.insert(metrics);
 | 
						|
    }
 | 
						|
 | 
						|
    destroy() {
 | 
						|
        try {
 | 
						|
            clearInterval(this.timer);
 | 
						|
        } catch (e) {
 | 
						|
            // empty
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 | 
						|
 | 
						|
module.exports = ClientMetricsStore;
 |