runSharedRequest.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { Observable } from 'rxjs';
  2. import { DataQuery, PanelData, DataSourceApi } from '@grafana/ui';
  3. import { QueryRunnerOptions } from 'app/features/dashboard/state/PanelQueryRunner';
  4. import { DashboardQuery } from './types';
  5. import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
  6. import { LoadingState } from '@grafana/data';
  7. import { SHARED_DASHBODARD_QUERY } from './types';
  8. export function isSharedDashboardQuery(datasource: string | DataSourceApi) {
  9. if (!datasource) {
  10. // default datasource
  11. return false;
  12. }
  13. if (datasource === SHARED_DASHBODARD_QUERY) {
  14. return true;
  15. }
  16. const ds = datasource as DataSourceApi;
  17. return ds.meta && ds.meta.name === SHARED_DASHBODARD_QUERY;
  18. }
  19. export function runSharedRequest(options: QueryRunnerOptions): Observable<PanelData> {
  20. return new Observable<PanelData>(subscriber => {
  21. const dashboard = getDashboardSrv().getCurrent();
  22. const listenToPanelId = getPanelIdFromQuery(options.queries);
  23. if (!listenToPanelId) {
  24. subscriber.next(getQueryError('Missing panel reference ID'));
  25. return null;
  26. }
  27. const currentPanel = dashboard.getPanelById(options.panelId);
  28. const listenToPanel = dashboard.getPanelById(listenToPanelId);
  29. if (!listenToPanel) {
  30. subscriber.next(getQueryError('Unknown Panel: ' + listenToPanelId));
  31. return null;
  32. }
  33. const listenToRunner = listenToPanel.getQueryRunner();
  34. const subscription = listenToRunner.getData(false).subscribe({
  35. next: (data: PanelData) => {
  36. console.log('got data from other panel', data);
  37. subscriber.next(data);
  38. },
  39. });
  40. // If we are in fullscreen the other panel will not execute any queries
  41. // So we have to trigger it from here
  42. if (currentPanel.fullscreen) {
  43. const { datasource, targets } = listenToPanel;
  44. const modified = {
  45. ...options,
  46. datasource,
  47. panelId: listenToPanelId,
  48. queries: targets,
  49. };
  50. listenToRunner.run(modified);
  51. }
  52. return () => {
  53. console.log('runSharedRequest unsubscribe');
  54. subscription.unsubscribe();
  55. };
  56. });
  57. }
  58. function getPanelIdFromQuery(queries: DataQuery[]): number | undefined {
  59. if (!queries || !queries.length) {
  60. return undefined;
  61. }
  62. return (queries[0] as DashboardQuery).panelId;
  63. }
  64. function getQueryError(msg: string): PanelData {
  65. return {
  66. state: LoadingState.Error,
  67. series: [],
  68. error: { message: msg },
  69. };
  70. }