runSharedRequest.ts 2.5 KB

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