mirror of
https://github.com/grafana/grafana.git
synced 2025-07-31 17:12:10 +08:00
95 lines
2.6 KiB
TypeScript
95 lines
2.6 KiB
TypeScript
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,
|
|
};
|
|
}
|
|
}
|
|
}
|