@@ -6,17 +6,28 @@ import {
66 DataQueryRequest ,
77 DataQueryResponse ,
88 DataSourceApi ,
9+ MetricFindValue ,
910 DataSourceInstanceSettings ,
1011 ScopedVars ,
1112 TimeRange ,
1213} from '@grafana/data' ;
1314
14- import { MyQuery , MyDataSourceOptions , defaultQuery } from './types' ;
15+ import {
16+ MyQuery ,
17+ MyDataSourceOptions ,
18+ defaultQuery ,
19+ MyVariableQuery ,
20+ MultiValueVariable ,
21+ TextValuePair ,
22+ } from './types' ;
1523import { dateTime , MutableDataFrame , FieldType , DataFrame } from '@grafana/data' ;
1624import { getTemplateSrv } from '@grafana/runtime' ;
1725import _ from 'lodash' ;
26+ import { isEqual } from 'lodash' ;
1827import { flatten , isRFC3339_ISO6801 } from './util' ;
1928
29+ const supportedVariableTypes = [ 'constant' , 'custom' , 'query' , 'textbox' ] ;
30+
2031export class DataSource extends DataSourceApi < MyQuery , MyDataSourceOptions > {
2132 basicAuth : string | undefined ;
2233 withCredentials : boolean | undefined ;
@@ -290,4 +301,54 @@ export class DataSource extends DataSourceApi<MyQuery, MyDataSourceOptions> {
290301 }
291302 ) ;
292303 }
304+
305+ async metricFindQuery ( query : MyVariableQuery , options ?: any ) {
306+ const metricFindValues : MetricFindValue [ ] = [ ] ;
307+
308+ query = defaults ( query , defaultQuery ) ;
309+
310+ let payload = query . queryText ;
311+ payload = getTemplateSrv ( ) . replace ( payload , { ...this . getVariables } ) ;
312+
313+ const response = await this . postQuery ( query , payload ) ;
314+
315+ const docs : any [ ] = DataSource . getDocs ( response . results . data , query . dataPath ) ;
316+
317+ for ( const doc of docs ) {
318+ for ( const fieldName in doc ) {
319+ metricFindValues . push ( { text : doc [ fieldName ] } ) ;
320+ }
321+ }
322+
323+ return metricFindValues ;
324+ }
325+
326+ getVariables ( ) {
327+ const variables : { [ id : string ] : TextValuePair } = { } ;
328+ Object . values ( getTemplateSrv ( ) . getVariables ( ) ) . forEach ( variable => {
329+ if ( ! supportedVariableTypes . includes ( variable . type ) ) {
330+ console . warn ( `Variable of type "${ variable . type } " is not supported` ) ;
331+
332+ return ;
333+ }
334+
335+ const supportedVariable = variable as MultiValueVariable ;
336+
337+ let variableValue = supportedVariable . current . value ;
338+ if ( variableValue === '$__all' || isEqual ( variableValue , [ '$__all' ] ) ) {
339+ if ( supportedVariable . allValue === null || supportedVariable . allValue === '' ) {
340+ variableValue = supportedVariable . options . slice ( 1 ) . map ( textValuePair => textValuePair . value ) ;
341+ } else {
342+ variableValue = supportedVariable . allValue ;
343+ }
344+ }
345+
346+ variables [ supportedVariable . id ] = {
347+ text : supportedVariable . current . text ,
348+ value : variableValue ,
349+ } ;
350+ } ) ;
351+
352+ return variables ;
353+ }
293354}
0 commit comments