utils.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { createErrorNotification, createSuccessNotification } from '../../core/copy/appNotification';
  2. import { AppNotification } from '../../types';
  3. import { PanelModel } from '../dashboard/state';
  4. import { addLibraryPanel, updateLibraryPanel } from './state/api';
  5. import { LibraryElementDTO, PanelModelLibraryPanel } from './types';
  6. export function createPanelLibraryErrorNotification(message: string): AppNotification {
  7. return createErrorNotification(message);
  8. }
  9. export function createPanelLibrarySuccessNotification(message: string): AppNotification {
  10. return createSuccessNotification(message);
  11. }
  12. export function toPanelModelLibraryPanel(libraryPanelDto: LibraryElementDTO): PanelModelLibraryPanel {
  13. const { uid, name, meta, version } = libraryPanelDto;
  14. return { uid, name, meta, version };
  15. }
  16. export async function saveAndRefreshLibraryPanel(panel: PanelModel, folderId: number): Promise<LibraryElementDTO> {
  17. const panelSaveModel = toPanelSaveModel(panel);
  18. const savedPanel = await saveOrUpdateLibraryPanel(panelSaveModel, folderId);
  19. updatePanelModelWithUpdate(panel, savedPanel);
  20. return savedPanel;
  21. }
  22. function toPanelSaveModel(panel: PanelModel): any {
  23. let panelSaveModel = panel.getSaveModel();
  24. panelSaveModel = {
  25. libraryPanel: {
  26. name: panel.title,
  27. uid: undefined,
  28. },
  29. ...panelSaveModel,
  30. };
  31. return panelSaveModel;
  32. }
  33. function updatePanelModelWithUpdate(panel: PanelModel, updated: LibraryElementDTO): void {
  34. panel.restoreModel({
  35. ...updated.model,
  36. configRev: 0, // reset config rev, since changes have been saved
  37. libraryPanel: toPanelModelLibraryPanel(updated),
  38. title: panel.title,
  39. });
  40. panel.refresh();
  41. }
  42. function saveOrUpdateLibraryPanel(panel: any, folderId: number): Promise<LibraryElementDTO> {
  43. if (!panel.libraryPanel) {
  44. return Promise.reject();
  45. }
  46. if (panel.libraryPanel && panel.libraryPanel.uid === undefined) {
  47. return addLibraryPanel(panel, folderId!);
  48. }
  49. return updateLibraryPanel(panel);
  50. }