preview.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { Observable, of } from 'rxjs';
  2. import { catchError, map, share } from 'rxjs/operators';
  3. import {
  4. dataFrameFromJSON,
  5. DataFrameJSON,
  6. getDefaultTimeRange,
  7. LoadingState,
  8. PanelData,
  9. withLoadingIndicator,
  10. } from '@grafana/data';
  11. import { getBackendSrv, toDataQueryError } from '@grafana/runtime';
  12. import {
  13. CloudPreviewRuleRequest,
  14. GrafanaPreviewRuleRequest,
  15. isCloudPreviewRequest,
  16. isGrafanaPreviewRequest,
  17. PreviewRuleRequest,
  18. PreviewRuleResponse,
  19. } from '../types/preview';
  20. import { RuleFormType } from '../types/rule-form';
  21. export function previewAlertRule(request: PreviewRuleRequest): Observable<PreviewRuleResponse> {
  22. if (isCloudPreviewRequest(request)) {
  23. return previewCloudAlertRule(request);
  24. }
  25. if (isGrafanaPreviewRequest(request)) {
  26. return previewGrafanaAlertRule(request);
  27. }
  28. throw new Error('unsupported preview rule request');
  29. }
  30. type GrafanaPreviewRuleResponse = {
  31. instances: DataFrameJSON[];
  32. };
  33. function previewGrafanaAlertRule(request: GrafanaPreviewRuleRequest): Observable<PreviewRuleResponse> {
  34. const type = RuleFormType.grafana;
  35. return withLoadingIndicator({
  36. whileLoading: createResponse(type),
  37. source: getBackendSrv()
  38. .fetch<GrafanaPreviewRuleResponse>({
  39. method: 'POST',
  40. url: `/api/v1/rule/test/grafana`,
  41. data: request,
  42. })
  43. .pipe(
  44. map(({ data }) => {
  45. return createResponse(type, {
  46. state: LoadingState.Done,
  47. series: data.instances.map(dataFrameFromJSON),
  48. });
  49. }),
  50. catchError((error: Error) => {
  51. return of(
  52. createResponse(type, {
  53. state: LoadingState.Error,
  54. error: toDataQueryError(error),
  55. })
  56. );
  57. }),
  58. share()
  59. ),
  60. });
  61. }
  62. function createResponse(ruleType: RuleFormType, data: Partial<PanelData> = {}): PreviewRuleResponse {
  63. return {
  64. ruleType,
  65. data: {
  66. state: LoadingState.Loading,
  67. series: [],
  68. timeRange: getDefaultTimeRange(),
  69. ...data,
  70. },
  71. };
  72. }
  73. function previewCloudAlertRule(request: CloudPreviewRuleRequest): Observable<PreviewRuleResponse> {
  74. throw new Error('preview for cloud alerting rules is not implemented');
  75. }