You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.0 KiB

2 years ago
import { MetricResults, QueryType } from './metrics/metric';
import { Metric } from './metrics/metrics_factory';
import { queryDirect } from './services/direct_service';
import { queryGrafana } from './services/grafana_service';
import { BadRange } from './types';
5 years ago
export { Metric } from './metrics/metrics_factory';
export { Datasource } from './metrics/metric'
2 years ago
export { DatasourceUnavailable } from './types';
export { GrafanaUnavailable } from './services/grafana_service';
const CHUNK_SIZE = 50000;
/**
* @param metric to query to Grafana
* @returns { values: [time, value][], columns: string[] }
*/
export async function queryByMetric(
// TODO: check how did we wanna use `url` field
metric: Metric, url: string, from: number, to: number, queryType: QueryType,
// TODO: we need an abstract DatasourceConfig class which will differ in direct and grafana queries
apiKey?: string
): Promise<MetricResults> {
if(from > to) {
throw new BadRange(
`Data-kit got wrong range: from ${from} > to ${to}`,
metric.datasource.type,
url
);
}
if(from === to) {
console.warn(`Data-kit got from === to`);
}
let data: MetricResults = {
values: [],
columns: []
};
while(true) {
let query = metric.metricQuery.getQuery(from, to, CHUNK_SIZE, data.values.length);
let res: any;
// TODO: use polymorphic `query` method instead
switch(queryType) {
case QueryType.GRAFANA:
res = await queryGrafana(query, apiKey as string, metric.datasource);
break;
case QueryType.DIRECT:
res = await queryDirect(query, metric.datasource);
break;
default:
throw new Error(`Unknown query type: ${queryType}`);
}
let chunk = metric.metricQuery.getResults(res);
let values = chunk.values;
data.values = data.values.concat(values);
data.columns = chunk.columns;
if(values.length < CHUNK_SIZE) {
// because if we get less that we could, then there is nothing more
break;
}
}
return data;
}