makeAnalyticsFunction.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import {Organization} from 'sentry/types';
  2. import {Hooks} from 'sentry/types/hooks';
  3. import {trackAnalyticsEventV2} from 'sentry/utils/analytics';
  4. const hasAnalyticsDebug = () => window.localStorage?.getItem('DEBUG_ANALYTICS') === '1';
  5. type OptionalOrg = {
  6. organization: Organization | string | null;
  7. };
  8. type Options = Parameters<Hooks['analytics:track-event-v2']>[1];
  9. /**
  10. * Generates functions used to track an event for analytics.
  11. * Each function can only handle the event types specified by the
  12. * generic for EventParameters and the events in eventKeyToNameMap.
  13. * Can specifcy default options with the defaultOptions argument as well.
  14. * Can make orgnization required with the second generic.
  15. */
  16. export default function makeAnalyticsFunction<
  17. EventParameters extends Record<string, Record<string, any>>,
  18. OrgRequirement extends OptionalOrg = OptionalOrg
  19. >(
  20. eventKeyToNameMap: Record<keyof EventParameters, string | null>,
  21. defaultOptions?: Options
  22. ) {
  23. /**
  24. * Function used for analytics of specifc types determined from factory function
  25. * Uses the current session ID or generates a new one if startSession == true.
  26. * An analytics session corresponds to a single action funnel such as installation.
  27. * Tracking by session allows us to track individual funnel attempts for a single user.
  28. */
  29. return <EventKey extends keyof EventParameters & string>(
  30. eventKey: EventKey,
  31. analyticsParams: EventParameters[EventKey] & OrgRequirement,
  32. options?: Options
  33. ) => {
  34. const eventName = eventKeyToNameMap[eventKey];
  35. const params = {
  36. eventKey,
  37. eventName,
  38. ...analyticsParams,
  39. };
  40. if (hasAnalyticsDebug()) {
  41. // eslint-disable-next-line no-console
  42. console.log('analyticsEvent', params);
  43. }
  44. // only apply options if required to make mock assertions easier
  45. if (options || defaultOptions) {
  46. options = {...defaultOptions, ...options};
  47. trackAnalyticsEventV2(params, options);
  48. } else {
  49. trackAnalyticsEventV2(params);
  50. }
  51. };
  52. }