initDashboard.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. // Services & Utils
  2. import { createErrorNotification } from 'app/core/copy/appNotification';
  3. import { getBackendSrv } from 'app/core/services/backend_srv';
  4. import { DashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
  5. import { DashboardLoaderSrv } from 'app/features/dashboard/services/DashboardLoaderSrv';
  6. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  7. import { AnnotationsSrv } from 'app/features/annotations/annotations_srv';
  8. import { VariableSrv } from 'app/features/templating/variable_srv';
  9. import { KeybindingSrv } from 'app/core/services/keybindingSrv';
  10. // Actions
  11. import { updateLocation } from 'app/core/actions';
  12. import { notifyApp } from 'app/core/actions';
  13. import locationUtil from 'app/core/utils/location_util';
  14. import {
  15. dashboardInitFetching,
  16. dashboardInitCompleted,
  17. dashboardInitFailed,
  18. dashboardInitSlow,
  19. dashboardInitServices,
  20. } from './actions';
  21. // Types
  22. import { DashboardRouteInfo, StoreState, ThunkDispatch, ThunkResult, DashboardDTO } from 'app/types';
  23. import { DashboardModel } from './DashboardModel';
  24. export interface InitDashboardArgs {
  25. $injector: any;
  26. $scope: any;
  27. urlUid?: string;
  28. urlSlug?: string;
  29. urlType?: string;
  30. urlFolderId?: string;
  31. routeInfo: DashboardRouteInfo;
  32. fixUrl: boolean;
  33. }
  34. async function redirectToNewUrl(slug: string, dispatch: ThunkDispatch, currentPath: string) {
  35. const res = await getBackendSrv().getDashboardBySlug(slug);
  36. if (res) {
  37. let newUrl = res.meta.url;
  38. // fix solo route urls
  39. if (currentPath.indexOf('dashboard-solo') !== -1) {
  40. newUrl = newUrl.replace('/d/', '/d-solo/');
  41. }
  42. const url = locationUtil.stripBaseFromUrl(newUrl);
  43. dispatch(updateLocation({ path: url, partial: true, replace: true }));
  44. }
  45. }
  46. async function fetchDashboard(
  47. args: InitDashboardArgs,
  48. dispatch: ThunkDispatch,
  49. getState: () => StoreState
  50. ): Promise<DashboardDTO | null> {
  51. try {
  52. switch (args.routeInfo) {
  53. case DashboardRouteInfo.Home: {
  54. // load home dash
  55. const dashDTO: DashboardDTO = await getBackendSrv().get('/api/dashboards/home');
  56. // if user specified a custom home dashboard redirect to that
  57. if (dashDTO.redirectUri) {
  58. const newUrl = locationUtil.stripBaseFromUrl(dashDTO.redirectUri);
  59. dispatch(updateLocation({ path: newUrl, replace: true }));
  60. return null;
  61. }
  62. // disable some actions on the default home dashboard
  63. dashDTO.meta.canSave = false;
  64. dashDTO.meta.canShare = false;
  65. dashDTO.meta.canStar = false;
  66. return dashDTO;
  67. }
  68. case DashboardRouteInfo.Normal: {
  69. // for old db routes we redirect
  70. if (args.urlType === 'db') {
  71. redirectToNewUrl(args.urlSlug, dispatch, getState().location.path);
  72. return null;
  73. }
  74. const loaderSrv: DashboardLoaderSrv = args.$injector.get('dashboardLoaderSrv');
  75. const dashDTO: DashboardDTO = await loaderSrv.loadDashboard(args.urlType, args.urlSlug, args.urlUid);
  76. if (args.fixUrl && dashDTO.meta.url) {
  77. // check if the current url is correct (might be old slug)
  78. const dashboardUrl = locationUtil.stripBaseFromUrl(dashDTO.meta.url);
  79. const currentPath = getState().location.path;
  80. if (dashboardUrl !== currentPath) {
  81. // replace url to not create additional history items and then return so that initDashboard below isn't executed multiple times.
  82. dispatch(updateLocation({ path: dashboardUrl, partial: true, replace: true }));
  83. return null;
  84. }
  85. }
  86. return dashDTO;
  87. }
  88. case DashboardRouteInfo.New: {
  89. return getNewDashboardModelData(args.urlFolderId);
  90. }
  91. default:
  92. throw { message: 'Unknown route ' + args.routeInfo };
  93. }
  94. } catch (err) {
  95. dispatch(dashboardInitFailed({ message: 'Failed to fetch dashboard', error: err }));
  96. console.log(err);
  97. return null;
  98. }
  99. }
  100. /**
  101. * This action (or saga) does everything needed to bootstrap a dashboard & dashboard model.
  102. * First it handles the process of fetching the dashboard, correcting the url if required (causing redirects/url updates)
  103. *
  104. * This is used both for single dashboard & solo panel routes, home & new dashboard routes.
  105. *
  106. * Then it handles the initializing of the old angular services that the dashboard components & panels still depend on
  107. *
  108. */
  109. export function initDashboard(args: InitDashboardArgs): ThunkResult<void> {
  110. return async (dispatch, getState) => {
  111. // set fetching state
  112. dispatch(dashboardInitFetching());
  113. // Detect slow loading / initializing and set state flag
  114. // This is in order to not show loading indication for fast loading dashboards as it creates blinking/flashing
  115. setTimeout(() => {
  116. if (getState().dashboard.model === null) {
  117. dispatch(dashboardInitSlow());
  118. }
  119. }, 500);
  120. // fetch dashboard data
  121. const dashDTO = await fetchDashboard(args, dispatch, getState);
  122. // returns null if there was a redirect or error
  123. if (!dashDTO) {
  124. return;
  125. }
  126. // set initializing state
  127. dispatch(dashboardInitServices());
  128. // create model
  129. let dashboard: DashboardModel;
  130. try {
  131. dashboard = new DashboardModel(dashDTO.dashboard, dashDTO.meta);
  132. } catch (err) {
  133. dispatch(dashboardInitFailed({ message: 'Failed create dashboard model', error: err }));
  134. console.log(err);
  135. return;
  136. }
  137. // add missing orgId query param
  138. const storeState = getState();
  139. if (!storeState.location.query.orgId) {
  140. dispatch(updateLocation({ query: { orgId: storeState.user.orgId }, partial: true, replace: true }));
  141. }
  142. // init services
  143. const timeSrv: TimeSrv = args.$injector.get('timeSrv');
  144. const annotationsSrv: AnnotationsSrv = args.$injector.get('annotationsSrv');
  145. const variableSrv: VariableSrv = args.$injector.get('variableSrv');
  146. const keybindingSrv: KeybindingSrv = args.$injector.get('keybindingSrv');
  147. const unsavedChangesSrv = args.$injector.get('unsavedChangesSrv');
  148. const dashboardSrv: DashboardSrv = args.$injector.get('dashboardSrv');
  149. timeSrv.init(dashboard);
  150. annotationsSrv.init(dashboard);
  151. // template values service needs to initialize completely before
  152. // the rest of the dashboard can load
  153. try {
  154. await variableSrv.init(dashboard);
  155. } catch (err) {
  156. dispatch(notifyApp(createErrorNotification('Templating init failed', err)));
  157. console.log(err);
  158. }
  159. try {
  160. dashboard.processRepeats();
  161. dashboard.updateSubmenuVisibility();
  162. // handle auto fix experimental feature
  163. const queryParams = getState().location.query;
  164. if (queryParams.autofitpanels) {
  165. dashboard.autoFitPanels(window.innerHeight, queryParams.kiosk);
  166. }
  167. // init unsaved changes tracking
  168. unsavedChangesSrv.init(dashboard, args.$scope);
  169. keybindingSrv.setupDashboardBindings(args.$scope, dashboard);
  170. } catch (err) {
  171. dispatch(notifyApp(createErrorNotification('Dashboard init failed', err)));
  172. console.log(err);
  173. }
  174. // legacy srv state
  175. dashboardSrv.setCurrent(dashboard);
  176. // yay we are done
  177. dispatch(dashboardInitCompleted(dashboard));
  178. };
  179. }
  180. function getNewDashboardModelData(urlFolderId?: string): any {
  181. const data = {
  182. meta: {
  183. canStar: false,
  184. canShare: false,
  185. isNew: true,
  186. folderId: 0,
  187. },
  188. dashboard: {
  189. title: 'New dashboard',
  190. panels: [
  191. {
  192. type: 'add-panel',
  193. gridPos: { x: 0, y: 0, w: 12, h: 9 },
  194. title: 'Panel Title',
  195. },
  196. ],
  197. },
  198. };
  199. if (urlFolderId) {
  200. data.meta.folderId = parseInt(urlFolderId, 10);
  201. }
  202. return data;
  203. }