addToDashboard.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { DataFrame, DataQuery, DataSourceRef } from '@grafana/data';
  2. import { backendSrv } from 'app/core/services/backend_srv';
  3. import {
  4. getNewDashboardModelData,
  5. setDashboardToFetchFromLocalStorage,
  6. } from 'app/features/dashboard/state/initDashboard';
  7. import { DashboardDTO, ExplorePanelData } from 'app/types';
  8. export enum AddToDashboardError {
  9. FETCH_DASHBOARD = 'fetch-dashboard',
  10. SET_DASHBOARD_LS = 'set-dashboard-ls-error',
  11. }
  12. interface AddPanelToDashboardOptions {
  13. queries: DataQuery[];
  14. queryResponse: ExplorePanelData;
  15. datasource?: DataSourceRef;
  16. dashboardUid?: string;
  17. }
  18. function createDashboard(): DashboardDTO {
  19. const dto = getNewDashboardModelData();
  20. // getNewDashboardModelData adds by default the "add-panel" panel. We don't want that.
  21. dto.dashboard.panels = [];
  22. return dto;
  23. }
  24. export async function setDashboardInLocalStorage(options: AddPanelToDashboardOptions) {
  25. const panelType = getPanelType(options.queries, options.queryResponse);
  26. const panel = {
  27. targets: options.queries,
  28. type: panelType,
  29. title: 'New Panel',
  30. gridPos: { x: 0, y: 0, w: 12, h: 8 },
  31. datasource: options.datasource,
  32. };
  33. let dto: DashboardDTO;
  34. if (options.dashboardUid) {
  35. try {
  36. dto = await backendSrv.getDashboardByUid(options.dashboardUid);
  37. } catch (e) {
  38. throw AddToDashboardError.FETCH_DASHBOARD;
  39. }
  40. } else {
  41. dto = createDashboard();
  42. }
  43. dto.dashboard.panels = [panel, ...(dto.dashboard.panels ?? [])];
  44. try {
  45. setDashboardToFetchFromLocalStorage(dto);
  46. } catch {
  47. throw AddToDashboardError.SET_DASHBOARD_LS;
  48. }
  49. }
  50. const isVisible = (query: DataQuery) => !query.hide;
  51. const hasRefId = (refId: DataFrame['refId']) => (frame: DataFrame) => frame.refId === refId;
  52. function getPanelType(queries: DataQuery[], queryResponse: ExplorePanelData) {
  53. for (const { refId } of queries.filter(isVisible)) {
  54. // traceview is not supported in dashboards, skipping it for now.
  55. const hasQueryRefId = hasRefId(refId);
  56. if (queryResponse.graphFrames.some(hasQueryRefId)) {
  57. return 'timeseries';
  58. }
  59. if (queryResponse.logsFrames.some(hasQueryRefId)) {
  60. return 'logs';
  61. }
  62. if (queryResponse.nodeGraphFrames.some(hasQueryRefId)) {
  63. return 'nodeGraph';
  64. }
  65. if (queryResponse.traceFrames.some(hasQueryRefId)) {
  66. return 'traces';
  67. }
  68. }
  69. // falling back to table
  70. return 'table';
  71. }