-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatasource.ts
66 lines (53 loc) · 1.93 KB
/
datasource.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { DataQueryRequest, DataSourceInstanceSettings, MetricFindValue, ScopedVars } from '@grafana/data';
import { DataSourceWithBackend, getTemplateSrv } from '@grafana/runtime';
import { TpDataSourceOptions, TpQuery, TpVariableQuery } from './types';
export class DataSource extends DataSourceWithBackend<TpQuery, TpDataSourceOptions> {
constructor(instanceSettings: DataSourceInstanceSettings<TpDataSourceOptions>) {
super(instanceSettings);
}
metricFindQuery(query: TpVariableQuery, options?: any) {
let metrics: MetricFindValue[] = []
if (!query || !options.variable.datasource) {
return Promise.resolve(metrics);
}
const prom = new Promise<MetricFindValue[]>((resolve) => {
const req = {
targets: [{ datasource: options.variable.datasource,
sql: query.query,
refId: String(Math.random()) }],
range: options ? options.range : (getTemplateSrv() as any).timeRange,
} as DataQueryRequest<TpQuery> ;
this.query(req).subscribe((res) => {
const result = res.data[0] || { fields: [] }
if (result.fields.length === 2) {
for (let i = 0; i < result.fields[0].values.length; i++) {
metrics.push({
text: result.fields[1].values[i],
value: result.fields[0].values[i]
})
}
} else if (result.fields.length === 1) {
metrics = result.fields[0].values.map((v: string) => {
return {
text: v,
value: v
}});
}
resolve(metrics);
});
})
return prom
}
applyTemplateVariables(query: TpQuery, scopedVars: ScopedVars) {
const srv = getTemplateSrv()
const sql = srv.replace(query.sql, scopedVars)
return {
...query,
sql: sql,
};
}
filterQuery(query: TpQuery): boolean {
// if no query has been provided, prevent the query from being executed
return !!query.sql;
}
}