All files / src/lib/routes/admin-api client-metrics.ts

100% Statements 21/21
100% Branches 4/4
100% Functions 4/4
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 69 70 71 72 73  59x                     59x   59x               141x 141x   141x   141x 141x       7x 7x 7x       7x               2x 2x 2x               7x 2x     5x   5x       3x         59x  
import { Request, Response } from 'express';
import Controller from '../controller';
import { IUnleashConfig } from '../../types/option';
import { IUnleashServices } from '../../types';
import { Logger } from '../../logger';
import ClientMetricsServiceV2 from '../../services/client-metrics/metrics-service-v2';
 
class ClientMetricsController extends Controller {
    private logger: Logger;
 
    private metrics: ClientMetricsServiceV2;
 
    private static HOURS_BACK_MIN = 1;
 
    private static HOURS_BACK_MAX = 48;
 
    constructor(
        config: IUnleashConfig,
        {
            clientMetricsServiceV2,
        }: Pick<IUnleashServices, 'clientMetricsServiceV2'>,
    ) {
        super(config);
        this.logger = config.getLogger('/admin-api/client-metrics.ts');
 
        this.metrics = clientMetricsServiceV2;
 
        this.get('/features/:name/raw', this.getRawToggleMetrics);
        this.get('/features/:name', this.getToggleMetricsSummary);
    }
 
    async getRawToggleMetrics(req: Request, res: Response): Promise<void> {
        const { name } = req.params;
        const { hoursBack } = req.query;
        const data = await this.metrics.getClientMetricsForToggle(
            name,
            this.parseHoursBackQueryParam(hoursBack),
        );
        res.json({
            version: 1,
            maturity: 'stable',
            data,
        });
    }
 
    async getToggleMetricsSummary(req: Request, res: Response): Promise<void> {
        const { name } = req.params;
        const data = await this.metrics.getFeatureToggleMetricsSummary(name);
        res.json({
            version: 1,
            maturity: 'stable',
            ...data,
        });
    }
 
    private parseHoursBackQueryParam(param: unknown): number | undefined {
        if (typeof param !== 'string') {
            return undefined;
        }
 
        const parsed = Number(param);
 
        if (
            parsed >= ClientMetricsController.HOURS_BACK_MIN &&
            parsed <= ClientMetricsController.HOURS_BACK_MAX
        ) {
            return parsed;
        }
    }
}
 
export default ClientMetricsController;