You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RouteRegistry.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Object describing application route.
  3. *
  4. * @typedef {Object} Route
  5. * @property {Component} component - React Component constructor.
  6. * @property {string} path - URL route, required for web routing.
  7. */
  8. /**
  9. * A registry for Navigator routes, allowing features to register themselves
  10. * without needing to create additional inter-feature dependencies.
  11. */
  12. class RouteRegistry {
  13. /**
  14. * Initializes a new RouteRegistry instance.
  15. */
  16. constructor() {
  17. /**
  18. * The set of registered routes.
  19. *
  20. * @private
  21. */
  22. this._routeRegistry = new Set();
  23. }
  24. /**
  25. * Returns all registered routes.
  26. *
  27. * @returns {Route[]}
  28. */
  29. getRoutes() {
  30. // We use the destructuring operator to 'clone' the route object to
  31. // prevent modifications from outside (e.g. React Native's Navigator
  32. // extends it with additional properties).
  33. return [ ...this._routeRegistry ].map(r => {
  34. return { ...r };
  35. });
  36. }
  37. /**
  38. * Returns registered route by name if any.
  39. *
  40. * @param {Object} component - The React Component (class) of the route to
  41. * retrieve.
  42. * @returns {Route|null}
  43. */
  44. getRouteByComponent(component) {
  45. const route
  46. = [ ...this._routeRegistry ].find(r => r.component === component);
  47. // We use destructuring operator to 'clone' route object to prevent
  48. // modifications from outside (e.g. React Native's Navigator extends
  49. // it with some additional properties).
  50. return route ? { ...route } : null;
  51. }
  52. /**
  53. * Adds a route to this registry.
  54. *
  55. * @param {Route} route - Route definition object.
  56. * @returns {void}
  57. */
  58. register(route) {
  59. if (this._routeRegistry.has(route)) {
  60. throw new Error(`Route ${route.component} is registered already!`);
  61. }
  62. this._routeRegistry.add(route);
  63. }
  64. }
  65. /**
  66. * The public singleton instance of the RouteRegistry class.
  67. */
  68. export default new RouteRegistry();