routeAnalytics.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import type {Location} from 'history';
  2. import capitalize from 'lodash/capitalize';
  3. import snakeCase from 'lodash/snakeCase';
  4. import type {PlainRoute} from 'sentry/types/legacyReactRouter';
  5. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  6. /**
  7. * This converts parameters in a route to be the upper version of it with a slight adjustment with IDs
  8. * some_word becomes SomeWord
  9. * And :projectId becomes :ProjectId
  10. */
  11. const camelCaseRouteParameter = (word: string) => {
  12. const tokens = word.match(/:(\w+)/);
  13. if (tokens) {
  14. const idToken = tokens[1]!;
  15. // only capitalize the first letter of the id
  16. // to keep 'Id' instead of 'id'
  17. return `:${capitalize(idToken[0])}${idToken.slice(1)}`;
  18. }
  19. return capitalize(word);
  20. };
  21. /**
  22. * @param routes Routes from React Router
  23. * @returns A string representing the route path
  24. * Ex: /organizations/:orgid/alerts/new/:alerttype/ ->
  25. * Organizations :orgid Alerts New :alerttype
  26. */
  27. export function getEventPath(routes: PlainRoute[]) {
  28. const routeString = getRouteStringFromRoutes(routes);
  29. return routeString
  30. .split('/')
  31. .map(camelCaseRouteParameter)
  32. .filter(s => !!s)
  33. .join(' ');
  34. }
  35. /**
  36. * @param location Location from React Router
  37. * @returns A string representing the route path
  38. */
  39. export function getUrlFromLocation(location: Location) {
  40. const previousUrlObj = new URL(window.location.origin + location.pathname);
  41. previousUrlObj.search = location.search;
  42. previousUrlObj.hash = location.hash;
  43. return previousUrlObj.toString();
  44. }
  45. /**
  46. * @param string representing the route path in Amplitude format
  47. * @return Reload representation of the route path
  48. * Ex: Organizations :OrgId Alerts New :AlertType ->
  49. * organizations.:org_id.alerts.new.:alert_type
  50. */
  51. export function convertToReloadPath(routeString: string) {
  52. return routeString
  53. .split(' ')
  54. .map(tok => tok.replace(/[\w ]+/g, snakeCase))
  55. .join('.');
  56. }