executeAnnotationQuery.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { Observable, of } from 'rxjs';
  2. import { map, mergeMap } from 'rxjs/operators';
  3. import { CoreApp, DataQueryRequest, DataSourceApi, rangeUtil, ScopedVars } from '@grafana/data';
  4. import { runRequest } from '../query/state/runRequest';
  5. import { standardAnnotationSupport } from './standardAnnotationSupport';
  6. import { AnnotationQueryOptions, AnnotationQueryResponse } from './types';
  7. let counter = 100;
  8. function getNextRequestId() {
  9. return 'AQ' + counter++;
  10. }
  11. export function executeAnnotationQuery(
  12. options: AnnotationQueryOptions,
  13. datasource: DataSourceApi,
  14. savedJsonAnno: any
  15. ): Observable<AnnotationQueryResponse> {
  16. const processor = {
  17. ...standardAnnotationSupport,
  18. ...datasource.annotations,
  19. };
  20. const annotation = processor.prepareAnnotation!(savedJsonAnno);
  21. if (!annotation) {
  22. return of({});
  23. }
  24. const query = processor.prepareQuery!(annotation);
  25. if (!query) {
  26. return of({});
  27. }
  28. // No more points than pixels
  29. const maxDataPoints = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  30. // Add interval to annotation queries
  31. const interval = rangeUtil.calculateInterval(options.range, maxDataPoints, datasource.interval);
  32. const scopedVars: ScopedVars = {
  33. __interval: { text: interval.interval, value: interval.interval },
  34. __interval_ms: { text: interval.intervalMs.toString(), value: interval.intervalMs },
  35. __annotation: { text: annotation.name, value: annotation },
  36. };
  37. const queryRequest: DataQueryRequest = {
  38. startTime: Date.now(),
  39. requestId: getNextRequestId(),
  40. range: options.range,
  41. maxDataPoints,
  42. scopedVars,
  43. ...interval,
  44. app: CoreApp.Dashboard,
  45. timezone: options.dashboard.timezone,
  46. targets: [
  47. {
  48. ...query,
  49. refId: 'Anno',
  50. },
  51. ],
  52. };
  53. return runRequest(datasource, queryRequest).pipe(
  54. mergeMap((panelData) => {
  55. if (!panelData.series) {
  56. return of({ panelData, events: [] });
  57. }
  58. return processor.processEvents!(annotation, panelData.series).pipe(map((events) => ({ panelData, events })));
  59. })
  60. );
  61. }