From 3fb5bd2a48eadcf84c136370b8e24e15cea9b7af Mon Sep 17 00:00:00 2001 From: ZuperZee Date: Tue, 23 Feb 2021 15:24:59 +0100 Subject: [PATCH] feat(getMetricValueByName): get metric from label When using transform, the metrics that are not transformed have their metric name in labels. --- src/utils/field.ts | 5 ++++- src/utils/getMetricValueByName.test.ts | 14 +++++++++++++- src/utils/getMetricValueByName.ts | 6 +++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/utils/field.ts b/src/utils/field.ts index cd35259..717c091 100644 --- a/src/utils/field.ts +++ b/src/utils/field.ts @@ -1,4 +1,4 @@ -import { Field, FieldCalcs, FieldType, ReducerID } from "@grafana/data"; +import { Field, FieldCalcs, FieldType, Labels, ReducerID } from "@grafana/data"; export const TIME_FIELD = field({ name: "Time", @@ -10,15 +10,18 @@ export function field({ name, type, calcs, + labels, }: { name: string; type: FieldType; calcs: FieldCalcs; + labels?: Labels; }): Field { return { name, type, config: {}, + labels: labels, values: { length: 0, get: (index: number) => { diff --git a/src/utils/getMetricValueByName.test.ts b/src/utils/getMetricValueByName.test.ts index 6d48d61..7aacf02 100644 --- a/src/utils/getMetricValueByName.test.ts +++ b/src/utils/getMetricValueByName.test.ts @@ -41,6 +41,12 @@ window.data = { type: FieldType.number, calcs: { [ReducerID.last]: 200 }, }), + field({ + name: "Value", + type: FieldType.number, + calcs: { [ReducerID.last]: 300 }, + labels: { name: "label-1" }, + }), ], length: 1, }, @@ -71,8 +77,14 @@ describe("getMetricValueByName", () => { }); describe("field name", () => { - it("gets correct value from field names", () => { + it("gets correct value from field name", () => { expect(getMetricValueByName("field-1")).toEqual(100); }); }); + + describe("label name", () => { + it("gets correct value from label name", () => { + expect(getMetricValueByName("label-1")).toEqual(300); + }); + }); }); diff --git a/src/utils/getMetricValueByName.ts b/src/utils/getMetricValueByName.ts index 820a6d0..693e459 100644 --- a/src/utils/getMetricValueByName.ts +++ b/src/utils/getMetricValueByName.ts @@ -8,7 +8,11 @@ function getSeriesByName(seriesName: string) { function getFieldByName(fieldName: string): Field | undefined { for (const series of data.series) { - const valueField = series.fields.find((field) => field.name == fieldName); + const valueField = series.fields.find((field) => + [field.name, ...(field.labels ? [field.labels.name] : [])].includes( + fieldName + ) + ); if (valueField) return valueField; } }