annotations_srv.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. ///<reference path="../../headers/common.d.ts" />
  2. import './editor_ctrl';
  3. import angular from 'angular';
  4. import _ from 'lodash';
  5. import $ from 'jquery';
  6. import coreModule from 'app/core/core_module';
  7. export class AnnotationsSrv {
  8. globalAnnotationsPromise: any;
  9. /** @ngInject */
  10. constructor(private $rootScope,
  11. private $q,
  12. private datasourceSrv,
  13. private timeSrv) {
  14. $rootScope.onAppEvent('refresh', this.clearCache.bind(this), $rootScope);
  15. $rootScope.onAppEvent('dashboard-initialized', this.clearCache.bind(this), $rootScope);
  16. }
  17. clearCache() {
  18. this.globalAnnotationsPromise = null;
  19. }
  20. getAnnotations(dashboard) {
  21. if (dashboard.annotations.list.length === 0) {
  22. return this.$q.when(null);
  23. }
  24. if (this.globalAnnotationsPromise) {
  25. return this.globalAnnotationsPromise;
  26. }
  27. var annotations = _.where(dashboard.annotations.list, {enable: true});
  28. var range = this.timeSrv.timeRange();
  29. var rangeRaw = this.timeSrv.timeRange(false);
  30. this.globalAnnotationsPromise = this.$q.all(_.map(annotations, annotation => {
  31. if (annotation.snapshotData) {
  32. return this.translateQueryResult(annotation.snapshotData);
  33. }
  34. return this.datasourceSrv.get(annotation.datasource).then(datasource => {
  35. // issue query against data source
  36. return datasource.annotationQuery({
  37. range: range,
  38. rangeRaw:
  39. rangeRaw,
  40. annotation: annotation
  41. });
  42. })
  43. .then(results => {
  44. // store response in annotation object if this is a snapshot call
  45. if (dashboard.snapshot) {
  46. annotation.snapshotData = angular.copy(results);
  47. }
  48. // translate result
  49. return this.translateQueryResult(results);
  50. });
  51. }))
  52. .then(allResults => {
  53. return _.flatten(allResults);
  54. }).catch(err => {
  55. this.$rootScope.appEvent('alert-error', ['Annotations failed', (err.message || err)]);
  56. });
  57. return this.globalAnnotationsPromise;
  58. }
  59. translateQueryResult(results) {
  60. var translated = [];
  61. for (var item of results) {
  62. translated.push({
  63. annotation: item.annotation,
  64. min: item.time,
  65. max: item.time,
  66. eventType: item.annotation.name,
  67. title: item.title,
  68. tags: item.tags,
  69. text: item.text,
  70. score: 1
  71. });
  72. }
  73. return translated;
  74. }
  75. }
  76. coreModule.service('annotationsSrv', AnnotationsSrv);