reactjs - Query Text Field Not Displaying in Variable Query Editor for Grafana Plugin - Stack Overflow

Description:I am developing a plugin for Grafana to fetch and display data from MongoDB. Everything wo

Description: I am developing a plugin for Grafana to fetch and display data from MongoDB. Everything works as expected, except for one issue when creating a variable in the Grafana dashboard. The "Query Text" field in the Variable Query Editor does not display correctly.

It seems there might be an issue with the connection between the frontend code in VariableQueryEditor.tsx and the backend code in datasource.go. image

Problem:

When enabling the "Is Variable" option, related fields appear, but the field for writing the Query Text does not render as expected. Question:

Is there an issue in my VariableQueryEditor.tsx implementation? How can I align the MetricFindQuery function in the datasource.go file with Grafana to make variables work correctly?

//VariableQueryEditor.tsx

import React, { ChangeEvent } from 'react';
import { VerticalGroup, InlineField, InlineFieldRow, Input, Checkbox, TextArea, Button } from '@grafana/ui';
import { QueryEditorProps } from '@grafana/data';
import { DataSource } from '../datasource';
import { MyDataSourceOptions, MyQuery } from '../types';

type Props = QueryEditorProps<DataSource, MyQuery, MyDataSourceOptions>;

export function VariableQueryEditor({ query, onChange, onRunQuery }: Props) {
  const onVariableFieldChange = (event: ChangeEvent<HTMLInputElement>) => {
    onChange({ ...query, variableField: event.target.value });
  };

  const onQueryTextChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
    onChange({ ...query, queryText: event.target.value });
  };

  const onIsVariableChange = (event: ChangeEvent<HTMLInputElement>) => {
    onChange({ ...query, isVariable: event.target.checked });
  };

  const { variableField, queryText, isVariable } = query;

  return (
    <div className="gf-form">
      <VerticalGroup spacing="sm">
        <InlineFieldRow>
          <InlineField label="Is Variable">
            <Checkbox onChange={onIsVariableChange} value={isVariable || false} />
          </InlineField>
        </InlineFieldRow>
        
        {isVariable && (
          <InlineFieldRow>
            <InlineField label="Variable Field">
              <Input 
                onChange={onVariableFieldChange} 
                value={variableField || ''} 
                placeholder="Field name for variable options" 
                autoComplete="off" 
              />
            </InlineField>
          </InlineFieldRow>
        )}

        <InlineFieldRow style={{ width: '100%' }}>
          <InlineField grow style={{ width: '100%' }}>
            <TextArea
              onChange={onQueryTextChange}
              value={queryText || ''} 
              placeholder="Enter a query…" 
              rows={8}
            />
          </InlineField>
        </InlineFieldRow>

        <InlineFieldRow>
          <Button variant="secondary" onClick={onRunQuery}>
            Run Query
          </Button>
        </InlineFieldRow>
      </VerticalGroup>
    </div>
  );
}

//module.ts
import { DataSourcePlugin } from '@grafana/data';
import { DataSource } from './datasource';
import { ConfigEditor } from './components/ConfigEditor';
import { QueryEditor } from './components/QueryEditor';
import { VariableQueryEditor } from './components/VariableQueryEditor';
import { MyQuery, MyDataSourceOptions } from './types';

export const plugin = new DataSourcePlugin<DataSource, MyQuery, MyDataSourceOptions>(DataSource)
  .setConfigEditor(ConfigEditor)
  .setQueryEditor(QueryEditor)
  .setVariableQueryEditor(VariableQueryEditor as any);

//datasource.go

func (d *Datasource) MetricFindQuery(ctx context.Context, query backend.DataQuery) backend.DataResponse {
    var queryData queryModel
    if err := json.Unmarshal(query.JSON, &queryData); err != nil {
        return newErrorResponse(backend.StatusBadRequest, fmt.Errorf("invalid query JSON: %v", err))
    }

    collection := d.getCollection(queryData.Database, queryData.Collection)
    if collection == nil {
        return newErrorResponse(backend.StatusBadRequest, fmt.Errorf("invalid collection"))
    }

    pipeline := mongo.Pipeline{
        bson.D{
            {Key: "$group", Value: bson.D{
                {Key: "_id", Value: "$" + queryData.VariableField},
            }},
        },
    }

    cursor, err := collection.Aggregate(ctx, pipeline)
    if err != nil {
        log.DefaultLogger.Error("Error executing aggregation:", err)
        return newErrorResponse(backend.StatusBadRequest, err)
    }
    defer cursor.Close(ctx)

    var results []string
    for cursor.Next(ctx) {
        var result struct {
            ID string `bson:"_id"`
        }
        if err := cursor.Decode(&result); err != nil {
            log.DefaultLogger.Error("Decode error:", err)
            continue
        }
        results = append(results, result.ID)
    }

    return createVariableResponse(results)
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745649001a4638146.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信