|
1 |
| -import { DataSourceInstanceSettings, ScopedVars } from '@grafana/data'; |
2 |
| -import { DataSourceWithBackend, getTemplateSrv } from '@grafana/runtime'; |
3 |
| -import { MyDataSourceOptions, MyQuery } from './types'; |
| 1 | +import {DataFrame, DataQueryRequest, DataSourceInstanceSettings, MetricFindValue, ScopedVars} from '@grafana/data'; |
| 2 | +import {DataSourceWithBackend, getTemplateSrv} from '@grafana/runtime'; |
| 3 | +import {MyDataSourceOptions, MyQuery} from './types'; |
| 4 | +import {map, switchMap} from 'rxjs/operators'; |
| 5 | +import {firstValueFrom} from 'rxjs'; |
4 | 6 |
|
5 | 7 | export class DataSource extends DataSourceWithBackend<MyQuery, MyDataSourceOptions> {
|
6 |
| - constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) { |
7 |
| - super(instanceSettings); |
8 |
| - } |
9 |
| - applyTemplateVariables(query: MyQuery, scopedVars: ScopedVars) { |
10 |
| - const templateSrv = getTemplateSrv(); |
11 |
| - return { |
12 |
| - ...query, |
13 |
| - rawSqlQuery: query.rawSqlQuery ? templateSrv.replace(query.rawSqlQuery, scopedVars) : '' |
14 |
| - }; |
15 |
| - } |
| 8 | + constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) { |
| 9 | + super(instanceSettings); |
| 10 | + } |
| 11 | + |
| 12 | + applyTemplateVariables(query: MyQuery, scopedVars: ScopedVars) { |
| 13 | + const templateSrv = getTemplateSrv(); |
| 14 | + return { |
| 15 | + ...query, |
| 16 | + rawSqlQuery: query.rawSqlQuery ? templateSrv.replace(query.rawSqlQuery, scopedVars) : '' |
| 17 | + }; |
| 18 | + } |
| 19 | + |
| 20 | + async metricFindQuery(queryText: string, options?: any): Promise<MetricFindValue[]> { |
| 21 | + if (!queryText) { |
| 22 | + return Promise.resolve([]); |
| 23 | + } |
| 24 | + |
| 25 | + return firstValueFrom(this.query({ |
| 26 | + targets: [ |
| 27 | + { |
| 28 | + rawSqlQuery: getTemplateSrv().replace(queryText, options.scopedVars), |
| 29 | + refId: 'metricFindQuery' |
| 30 | + }, |
| 31 | + ], |
| 32 | + maxDataPoints: 0, |
| 33 | + } as DataQueryRequest<MyQuery>) |
| 34 | + .pipe( |
| 35 | + switchMap((response) => { |
| 36 | + if (response.error) { |
| 37 | + console.log('Error: ' + response.error.message); |
| 38 | + throw new Error(response.error.message); |
| 39 | + } |
| 40 | + return response.data; |
| 41 | + }), |
| 42 | + switchMap((data: DataFrame) => { |
| 43 | + return data.fields; |
| 44 | + }), |
| 45 | + map((field) => |
| 46 | + field.values.toArray().map((value) => { |
| 47 | + return {text: value}; |
| 48 | + }) |
| 49 | + ) |
| 50 | + )); |
| 51 | + } |
16 | 52 | }
|
0 commit comments