import React, { PureComponent, ChangeEvent } from 'react'; import { QueryEditorProps, PanelData } from '@grafana/data'; import { LegacyForms, ValidationEvents, EventsWithValidation, Icon } from '@grafana/ui'; const { Input, Switch } = LegacyForms; import { CloudWatchQuery, CloudWatchMetricsQuery, CloudWatchJsonData, ExecutedQueryPreview } from '../types'; import { CloudWatchDatasource } from '../datasource'; import { QueryField, Alias, MetricsQueryFieldsEditor } from './'; export type Props = QueryEditorProps; interface State { showMeta: boolean; } const idValidationEvents: ValidationEvents = { [EventsWithValidation.onBlur]: [ { rule: (value) => new RegExp(/^$|^[a-z][a-zA-Z0-9_]*$/).test(value), errorMessage: 'Invalid format. Only alphanumeric characters and underscores are allowed', }, ], }; export const normalizeQuery = ({ namespace, metricName, expression, dimensions, region, id, alias, statistic, period, ...rest }: CloudWatchMetricsQuery): CloudWatchMetricsQuery => { const normalizedQuery = { namespace: namespace || '', metricName: metricName || '', expression: expression || '', dimensions: dimensions || {}, region: region || 'default', id: id || '', alias: alias || '', statistic: statistic ?? 'Average', period: period || '', ...rest, }; return !rest.hasOwnProperty('matchExact') ? { ...normalizedQuery, matchExact: true } : normalizedQuery; }; export class MetricsQueryEditor extends PureComponent { state: State = { showMeta: false }; componentDidMount(): void { const metricsQuery = this.props.query as CloudWatchMetricsQuery; const query = normalizeQuery(metricsQuery); this.props.onChange(query); } onChange(query: CloudWatchMetricsQuery) { const { onChange, onRunQuery } = this.props; onChange(query); onRunQuery(); } getExecutedQueryPreview(data?: PanelData): ExecutedQueryPreview { if (!(data?.series.length && data?.series[0].meta?.custom)) { return { executedQuery: '', period: '', id: '', }; } return { executedQuery: data?.series[0].meta.executedQueryString ?? '', period: data.series[0].meta.custom['period'], id: data.series[0].meta.custom['id'], }; } render() { const { data, onRunQuery } = this.props; const metricsQuery = this.props.query as CloudWatchMetricsQuery; const { showMeta } = this.state; const query = normalizeQuery(metricsQuery); const executedQueryPreview = this.getExecutedQueryPreview(data); return ( <>
) => this.onChange({ ...metricsQuery, id: event.target.value }) } validationEvents={idValidationEvents} value={query.id} />
) => this.onChange({ ...metricsQuery, expression: event.target.value }) } />
) => this.onChange({ ...metricsQuery, period: event.target.value }) } />
this.onChange({ ...metricsQuery, alias: value })} /> this.onChange({ ...metricsQuery, matchExact: !metricsQuery.matchExact, }) } />
{showMeta && (
Metric Data Query ID Metric Data Query Expression Period
{executedQueryPreview.id} {executedQueryPreview.executedQuery} {executedQueryPreview.period}
)}
); } }