importPanelPlugin.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import * as grafanaData from '@grafana/data';
  2. import config from 'app/core/config';
  3. import { getPanelPluginLoadError } from '../panel/components/PanelPluginError';
  4. import { importPluginModule } from './plugin_loader';
  5. interface PanelCache {
  6. [key: string]: Promise<grafanaData.PanelPlugin>;
  7. }
  8. const panelCache: PanelCache = {};
  9. export function importPanelPlugin(id: string): Promise<grafanaData.PanelPlugin> {
  10. const loaded = panelCache[id];
  11. if (loaded) {
  12. return loaded;
  13. }
  14. const meta = config.panels[id];
  15. if (!meta) {
  16. throw new Error(`Plugin ${id} not found`);
  17. }
  18. panelCache[id] = getPanelPlugin(meta);
  19. return panelCache[id];
  20. }
  21. export function importPanelPluginFromMeta(meta: grafanaData.PanelPluginMeta): Promise<grafanaData.PanelPlugin> {
  22. return getPanelPlugin(meta);
  23. }
  24. function getPanelPlugin(meta: grafanaData.PanelPluginMeta): Promise<grafanaData.PanelPlugin> {
  25. return importPluginModule(meta.module, meta.info?.version)
  26. .then((pluginExports) => {
  27. if (pluginExports.plugin) {
  28. return pluginExports.plugin as grafanaData.PanelPlugin;
  29. } else if (pluginExports.PanelCtrl) {
  30. const plugin = new grafanaData.PanelPlugin(null);
  31. plugin.angularPanelCtrl = pluginExports.PanelCtrl;
  32. return plugin;
  33. }
  34. throw new Error('missing export: plugin or PanelCtrl');
  35. })
  36. .then((plugin) => {
  37. plugin.meta = meta;
  38. return plugin;
  39. })
  40. .catch((err) => {
  41. // TODO, maybe a different error plugin
  42. console.warn('Error loading panel plugin: ' + meta.id, err);
  43. return getPanelPluginLoadError(meta, err);
  44. });
  45. }