Skip to content

Commit

Permalink
feat(getMetricValueByName): get metric from label
Browse files Browse the repository at this point in the history
When using transform,
the metrics that are not transformed have their metric name in labels.
  • Loading branch information
ZuperZee committed Feb 23, 2021
1 parent cc21775 commit 3fb5bd2
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/utils/field.ts
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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) => {
Expand Down
14 changes: 13 additions & 1 deletion src/utils/getMetricValueByName.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down Expand Up @@ -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);
});
});
});
6 changes: 5 additions & 1 deletion src/utils/getMetricValueByName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down

0 comments on commit 3fb5bd2

Please sign in to comment.