import React, { PureComponent, ChangeEvent } from 'react'; import isEmpty from 'lodash/isEmpty'; import { ExploreQueryFieldProps } from '@grafana/data'; import { LegacyForms, ValidationEvents, EventsWithValidation, Icon } from '@grafana/ui'; const { Input, Switch } = LegacyForms; import { CloudWatchQuery, CloudWatchMetricsQuery } from '../types'; import { CloudWatchDatasource } from '../datasource'; import { QueryField, Alias, MetricsQueryFieldsEditor } from './'; export type Props = ExploreQueryFieldProps; 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, statistics, period, ...rest }: CloudWatchMetricsQuery): CloudWatchMetricsQuery => { const normalizedQuery = { namespace: namespace || '', metricName: metricName || '', expression: expression || '', dimensions: dimensions || {}, region: region || 'default', id: id || '', alias: alias || '', statistics: isEmpty(statistics) ? ['Average'] : statistics, 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(); } render() { const { data, onRunQuery } = this.props; const metricsQuery = this.props.query as CloudWatchMetricsQuery; const { showMeta } = this.state; const query = normalizeQuery(metricsQuery); const metaDataExist = data && Object.values(data).length && data.state === 'Done'; return ( <> {query.statistics.length <= 1 && (
) => 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 && metaDataExist && ( {data?.series?.[0]?.meta?.gmdMeta?.map(({ ID, Expression, Period }: any) => ( ))}
Metric Data Query ID Metric Data Query Expression Period
{ID} {Expression} {Period}
)}
); } }