MetaAnalyticsBackend.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { EchoBackend, EchoEvent, EchoEventType, getBackendSrv, MetaAnalyticsEvent } from '@grafana/runtime';
  2. export interface MetaAnalyticsBackendOptions {
  3. url: string;
  4. }
  5. export class MetaAnalyticsBackend implements EchoBackend<MetaAnalyticsEvent, MetaAnalyticsBackendOptions> {
  6. private buffer: MetaAnalyticsEvent[] = [];
  7. supportedEvents = [EchoEventType.MetaAnalytics];
  8. constructor(public options: MetaAnalyticsBackendOptions) {}
  9. addEvent = (e: EchoEvent) => {
  10. this.buffer.push(e);
  11. };
  12. flush = () => {
  13. if (this.buffer.length === 0) {
  14. return;
  15. }
  16. const result: any[] = [];
  17. for (const event of this.buffer) {
  18. result.push({
  19. type: event.type,
  20. ...event.payload,
  21. meta: event.meta,
  22. });
  23. }
  24. // Currently we don have API for sending the metrics hence loging to console in dev environment
  25. if (process.env.NODE_ENV === 'development') {
  26. console.log('MetaAnalyticsBackend flushing:', result);
  27. }
  28. this.buffer = [];
  29. if (this.options.url) {
  30. getBackendSrv()
  31. .fetch({
  32. method: 'POST',
  33. url: this.options.url,
  34. showSuccessAlert: false,
  35. showErrorAlert: false,
  36. data: result,
  37. })
  38. .toPromise();
  39. }
  40. };
  41. }