makeAnalyticsFunction.tsx 2.0 KB

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