From f45df5d4229d424435bffaff570b3bac37c1f656 Mon Sep 17 00:00:00 2001 From: Lars Strojny Date: Thu, 24 Nov 2022 19:53:03 +0100 Subject: [PATCH] Clean up prefix handling --- src/prometheus.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/prometheus.ts b/src/prometheus.ts index 7ffdf7a..2ecb34e 100644 --- a/src/prometheus.ts +++ b/src/prometheus.ts @@ -3,7 +3,11 @@ import type { Logger } from 'homebridge' import type { HttpConfig, HttpResponse, HttpServer } from './adapters/http' export class MetricsRenderer { - constructor(private readonly prefix: string) {} + private readonly prefix: string + + constructor(prefix: string) { + this.prefix = trimRight(prefix, '_') + } render(metric: Metric): string { const name = this.metricName(metric.name) @@ -26,10 +30,14 @@ export class MetricsRenderer { private metricName(name: string): string { name = name.replace(/^(.*_)?(total)_(.*)$/, '$1$3_$2') - return sanitizePrometheusMetricName(stringReverse(stringReverse(this.prefix).replace(/^_+/, '')) + '_' + name) + return sanitizePrometheusMetricName(`${this.prefix}_${name}`) } } +function trimRight(str: string, char: string): string { + return stringReverse(stringReverse(str).replace(new RegExp(`^[${char}]+`), '')) +} + function stringReverse(str: string): string { return str.split('').reverse().join('') }