generatePath.js 572 B

123456789101112131415161718192021222324252627
  1. import pathToRegexp from "path-to-regexp";
  2. const cache = {};
  3. const cacheLimit = 10000;
  4. let cacheCount = 0;
  5. function compilePath(path) {
  6. if (cache[path]) return cache[path];
  7. const generator = pathToRegexp.compile(path);
  8. if (cacheCount < cacheLimit) {
  9. cache[path] = generator;
  10. cacheCount++;
  11. }
  12. return generator;
  13. }
  14. /**
  15. * Public API for generating a URL pathname from a path and parameters.
  16. */
  17. function generatePath(path = "/", params = {}) {
  18. return path === "/" ? path : compilePath(path)(params, { pretty: true });
  19. }
  20. export default generatePath;