The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
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.
grafana/e2e/test-plugins/grafana-test-datasource/datasource.ts

95 lines
2.6 KiB

import { getBackendSrv, isFetchError } from '@grafana/runtime';
import {
CoreApp,
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
createDataFrame,
FieldType,
} from '@grafana/data';
import { MyQuery, MyDataSourceOptions, DEFAULT_QUERY, DataSourceResponse } from './types';
import { lastValueFrom } from 'rxjs';
import { VariableSupport } from './variables';
export class DataSource extends DataSourceApi<MyQuery, MyDataSourceOptions> {
baseUrl: string;
constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) {
super(instanceSettings);
this.baseUrl = instanceSettings.url!;
this.variables = new VariableSupport();
}
getDefaultQuery(_: CoreApp): Partial<MyQuery> {
return DEFAULT_QUERY;
}
filterQuery(query: MyQuery): boolean {
// if no query has been provided, prevent the query from being executed
return !!query.queryText;
}
async query(options: DataQueryRequest<MyQuery>): Promise<DataQueryResponse> {
const { range } = options;
const from = range!.from.valueOf();
const to = range!.to.valueOf();
return {
data: [
createDataFrame({
refId: 'A',
fields: [
{ name: 'Time', values: [from, to], type: FieldType.time },
{ name: 'Value', values: ['A', 'B'], type: FieldType.string },
],
}),
],
};
}
async request(url: string, params?: string) {
const response = getBackendSrv().fetch<DataSourceResponse>({
url: `${this.baseUrl}${url}${params?.length ? `?${params}` : ''}`,
});
return lastValueFrom(response);
}
/**
* Checks whether we can connect to the API.
*/
async testDatasource() {
const defaultErrorMessage = 'Cannot connect to API';
try {
const response = await this.request('/health');
if (response.status === 200) {
return {
status: 'success',
message: 'Success',
};
} else {
return {
status: 'error',
message: response.statusText ? response.statusText : defaultErrorMessage,
};
}
} catch (err) {
let message = '';
if (typeof err === 'string') {
message = err;
} else if (isFetchError(err)) {
message = 'Fetch error: ' + (err.statusText ? err.statusText : defaultErrorMessage);
if (err.data && err.data.error && err.data.error.code) {
message += ': ' + err.data.error.code + '. ' + err.data.error.message;
}
}
return {
status: 'error',
message,
};
}
}
}