datasource_srv.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { Observable } from 'rxjs';
  2. import {
  3. DataQueryRequest,
  4. DataQueryResponse,
  5. DataSourceApi,
  6. DataSourceInstanceSettings,
  7. DataSourcePluginMeta,
  8. DataSourceRef,
  9. getDataSourceUID,
  10. } from '@grafana/data';
  11. export class DatasourceSrvMock {
  12. constructor(private defaultDS: DataSourceApi, private datasources: { [name: string]: DataSourceApi }) {
  13. //
  14. }
  15. get(ref?: DataSourceRef | string): Promise<DataSourceApi> {
  16. if (!ref) {
  17. return Promise.resolve(this.defaultDS);
  18. }
  19. const uid = getDataSourceUID(ref) ?? '';
  20. const ds = this.datasources[uid];
  21. if (ds) {
  22. return Promise.resolve(ds);
  23. }
  24. return Promise.reject(`Unknown Datasource: ${JSON.stringify(ref)}`);
  25. }
  26. }
  27. export class MockDataSourceApi extends DataSourceApi {
  28. result: DataQueryResponse = { data: [] };
  29. constructor(name?: string, result?: DataQueryResponse, meta?: any, private error: string | null = null) {
  30. super({ name: name ? name : 'MockDataSourceApi' } as DataSourceInstanceSettings);
  31. if (result) {
  32. this.result = result;
  33. }
  34. this.meta = meta || ({} as DataSourcePluginMeta);
  35. }
  36. query(request: DataQueryRequest): Promise<DataQueryResponse> {
  37. if (this.error) {
  38. return Promise.reject(this.error);
  39. }
  40. return new Promise((resolver) => {
  41. setTimeout(() => {
  42. resolver(this.result);
  43. });
  44. });
  45. }
  46. testDatasource() {
  47. return Promise.resolve();
  48. }
  49. }
  50. export class MockObservableDataSourceApi extends DataSourceApi {
  51. results: DataQueryResponse[] = [{ data: [] }];
  52. constructor(name?: string, results?: DataQueryResponse[], meta?: any, private error: string | null = null) {
  53. super({ name: name ? name : 'MockDataSourceApi' } as DataSourceInstanceSettings);
  54. if (results) {
  55. this.results = results;
  56. }
  57. this.meta = meta || ({} as DataSourcePluginMeta);
  58. }
  59. query(request: DataQueryRequest): Observable<DataQueryResponse> {
  60. return new Observable((observer) => {
  61. if (this.error) {
  62. observer.error(this.error);
  63. }
  64. if (this.results) {
  65. this.results.forEach((response) => observer.next(response));
  66. observer.complete();
  67. }
  68. });
  69. }
  70. testDatasource() {
  71. return Promise.resolve();
  72. }
  73. }