getRouteStringFromRoutes.tsx 982 B

12345678910111213141516171819202122232425262728293031
  1. import {PlainRoute} from 'react-router';
  2. import findLastIndex from 'lodash/findLastIndex';
  3. type RouteWithPath = Omit<PlainRoute, 'path'> & Required<Pick<PlainRoute, 'path'>>;
  4. /**
  5. * Creates a route string from an array of `routes` from react-router
  6. *
  7. * It will look for the last route path that begins with a `/` and
  8. * concatenate all of the following routes. Skips any routes without a path
  9. *
  10. * @param {Array<{}>} routes An array of route objects from react-router
  11. * @return String Returns a route path
  12. */
  13. export default function getRouteStringFromRoutes(routes?: PlainRoute[]): string {
  14. if (!Array.isArray(routes)) {
  15. return '';
  16. }
  17. const routesWithPaths = routes.filter((route): route is RouteWithPath => !!route.path);
  18. const lastAbsolutePathIndex = findLastIndex(routesWithPaths, ({path}) =>
  19. path.startsWith('/')
  20. );
  21. return routesWithPaths
  22. .slice(lastAbsolutePathIndex)
  23. .filter(({path}) => !!path)
  24. .map(({path}) => path)
  25. .join('');
  26. }