From ae850b21da55d3f5aad08dc4d86056383f93f1d7 Mon Sep 17 00:00:00 2001
From: Haohan Yang <37651510+haohanyang@users.noreply.github.com>
Date: Fri, 6 Dec 2024 07:17:31 +0100
Subject: [PATCH] Expand `value` field as variable result (#28)
---
src/components/VariableQueryEditor.tsx | 12 +++++++----
src/utils.ts | 28 ++++++++++----------------
2 files changed, 19 insertions(+), 21 deletions(-)
diff --git a/src/components/VariableQueryEditor.tsx b/src/components/VariableQueryEditor.tsx
index 269ec48..22ab249 100644
--- a/src/components/VariableQueryEditor.tsx
+++ b/src/components/VariableQueryEditor.tsx
@@ -1,6 +1,6 @@
import React, { useState } from "react";
-import { DEFAULT_QUERY, VariableQuery } from "../types";
-import { CodeEditor, Field, InlineField, Input } from "@grafana/ui";
+import { VariableQuery } from "../types";
+import { CodeEditor, Field, InlineField, Input, Button, Alert } from "@grafana/ui";
interface VariableQueryProps {
query: VariableQuery;
@@ -32,17 +32,21 @@ export const VariableQueryEditor = ({ onChange, query }: VariableQueryProps) =>
error="Please enter the collection" invalid={!query.collection}>
+
+ The query result is expected to contain value
field which has elements of type string
or number
+
+
>
);
};
diff --git a/src/utils.ts b/src/utils.ts
index f759563..da547ce 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -102,27 +102,21 @@ export function randomId(length: number) {
export function getMetricValues(response: DataQueryResponse): MetricFindValue[] {
const dataframe = response.data[0] as DataFrameSchema;
- const fields = dataframe.
- fields.filter(f => f.type === FieldType.string || f.type === FieldType.number)
- // @ts-ignore
- .filter(f => f.values && f.values.length > 0);
+ const field = dataframe.fields.find(f => f.name === "value");
- // @ts-ignore
- return fields.map(function (field) {
- // @ts-ignore
- const values: Array = field.values;
- let text: string;
+ if (!field) {
+ throw new Error("Field \"value\" not found");
+ }
- if (values.length === 1) {
- text = `${field.name}:${values[0]}`;
- } else {
- text = `${field.name}:[${values[0]}, ...]`;
- }
+ if (field.type !== FieldType.string && field.type !== FieldType.number) {
+ throw new Error("Each element should be string or number");
+ }
+ // @ts-ignore
+ return field.values.map((value: string | number) => {
return {
- text: text,
- // @ts-ignore
- value: values.length === 1 ? values[0] : values,
+ text: value.toString(),
+ value: value,
expandable: true
};
});