trackAmplitudeEvent.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import * as Amplitude from '@amplitude/analytics-browser';
  2. import ConfigStore from 'sentry/stores/configStore';
  3. // keep track of the last org id so we can update the group if it changes
  4. let lastOrganizationId: number | null = null;
  5. function trackAmplitudeEvent(
  6. event_type: string,
  7. organization_id: number | null | undefined,
  8. data: Record<PropertyKey, unknown>,
  9. eventOptions?: {time?: number}
  10. ) {
  11. // quit early if analytics is disabled
  12. if (!ConfigStore.get('enableAnalytics')) {
  13. return;
  14. }
  15. const user = ConfigStore.get('user');
  16. Amplitude.setUserId(user?.id ?? null);
  17. // Most of the time an event will be in the context of an org, and if so, we must attach
  18. // the org to the event to make amplitude's org-reporting work. To reduce the possibility
  19. // of error we require the caller to be explicit about the org. To intentionally not record
  20. // an org, organization_id can be set to null.
  21. if (organization_id === undefined) {
  22. return;
  23. }
  24. // if the org id has changed, we need to update the group
  25. if (organization_id !== lastOrganizationId) {
  26. Amplitude.setGroup('organization_id', organization_id?.toString() || '');
  27. lastOrganizationId = organization_id;
  28. }
  29. Amplitude.track(event_type, data, eventOptions);
  30. }
  31. export default trackAmplitudeEvent;