|
1 | | -import { DataSourceInstanceSettings, CoreApp } from '@grafana/data'; |
2 | | -import { DataSourceWithBackend } from '@grafana/runtime'; |
| 1 | +import { DataSourceInstanceSettings, CoreApp, ScopedVars, DataQueryRequest, DataFrame, Field, MetricFindValue } from '@grafana/data'; |
| 2 | +import { DataSourceWithBackend, getTemplateSrv } from '@grafana/runtime'; |
3 | 3 |
|
4 | | -import { HaystackQuery, HaystackDataSourceOptions, DEFAULT_QUERY } from './types'; |
| 4 | +import { HaystackQuery, HaystackDataSourceOptions, DEFAULT_QUERY, HaystackVariableQuery } from './types'; |
5 | 5 |
|
6 | 6 | export class DataSource extends DataSourceWithBackend<HaystackQuery, HaystackDataSourceOptions> { |
7 | 7 | constructor(instanceSettings: DataSourceInstanceSettings<HaystackDataSourceOptions>) { |
8 | 8 | super(instanceSettings); |
9 | 9 | } |
10 | 10 |
|
| 11 | + applyTemplateVariables(query: HaystackQuery, scopedVars: ScopedVars): Record<string, any> { |
| 12 | + return { |
| 13 | + ...query, |
| 14 | + eval: getTemplateSrv().replace(query.eval, scopedVars, "csv"), |
| 15 | + hisRead: getTemplateSrv().replace(query.hisRead, scopedVars, "csv"), |
| 16 | + read: getTemplateSrv().replace(query.read, scopedVars, "csv"), |
| 17 | + }; |
| 18 | + } |
| 19 | + |
| 20 | + // This is called when the user is selecting a variable value |
| 21 | + async metricFindQuery(query: HaystackVariableQuery, options?: any) { |
| 22 | + let request: HaystackQuery = { |
| 23 | + refId: "VariableQuery", |
| 24 | + type: "Eval", |
| 25 | + eval: query.eval, |
| 26 | + hisRead: "", |
| 27 | + read: "" |
| 28 | + }; |
| 29 | + let response = await this.query({ targets: [request] } as DataQueryRequest<HaystackQuery>).toPromise() |
| 30 | + |
| 31 | + if (response === undefined || response.data === undefined) { |
| 32 | + return []; |
| 33 | + } |
| 34 | + |
| 35 | + return response.data.reduce((acc: MetricFindValue[], frame: DataFrame) => { |
| 36 | + let field = frame.fields[0]; |
| 37 | + if (query.column !== undefined && query.column !== "") { |
| 38 | + // If a column was input, match the column name |
| 39 | + field = frame.fields.find((field: Field) => field.name === query.column) ?? field; |
| 40 | + } |
| 41 | + |
| 42 | + let fieldVals = field.values.toArray().map((value) => { |
| 43 | + if (value.startsWith("@")) { |
| 44 | + // Detect ref using @ prefix, and adjust value to just the Ref |
| 45 | + let spaceIndex = value.indexOf(" "); |
| 46 | + let id = value.substring(0, spaceIndex); |
| 47 | + return {text: value, value: id}; |
| 48 | + } else { |
| 49 | + // Otherwise, just use the value directly |
| 50 | + return {text: value, value: value}; |
| 51 | + } |
| 52 | + }); |
| 53 | + return acc.concat(fieldVals); |
| 54 | + }, []); |
| 55 | + } |
| 56 | + |
| 57 | + |
11 | 58 | getDefaultQuery(_: CoreApp): Partial<HaystackQuery> { |
12 | 59 | return DEFAULT_QUERY |
13 | 60 | } |
|
0 commit comments