Clean up prefix handling

This commit is contained in:
Lars Strojny 2022-11-24 19:53:03 +01:00
parent 65304798de
commit f45df5d422
No known key found for this signature in database
GPG key ID: 887416A2AD3B0CA9

View file

@ -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('')
}