npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

path-helper-util

v1.0.4

Published

A utility for managing and retrieving navigation paths.

Downloads

7

Readme

Path Helper Util

Sometimes our web apps have a lot of routes. This leads to us using anchor tags or link components throughout our projects. But what if we change one of those routes later? Do we want to manually have to sift through our code to find where we've created a link to that route so that we can update it? Wouldn't it be nicer if we had our paths in a central place so that we can update it once and that update is reflected throughout the project?

Path Helper Util does just that, it's a utility for managing and retrieving navigation paths within your application. This package allows you to define, register, and extract paths based on navigation names and groups, providing a centralised way to handle routes. It's also written in typescript, so it's type safe, too.

Table of Contents

Installation

To install the package, run:

npm i path-helper-util

Exported Types

A number of types are exposed for your use:

PathFunction

Represents a function that returns a string path. These are used to return paths when required.

type PathFunction = (...args: (string | number | undefined)[]) => string;

Path

Represents a path object. You'll follow this structure when registering and extracting a path.

interface Path {
  path: PathFunction;
  label: string;
  navs: string[];
  group?: string;
}

Paths

Represents a collection of paths. If you extract all paths as a single object using .getPaths(), this is what you'll get.

interface Paths {
  [key: string]: Path;
}

NavLink

Represents a navigation link. This type represents the outputs of extraction functions.

interface NavLink {
  path: PathFunction;
  label: string;
  group?: string;
}

Exported Singleton

pathHelper

A singleton instance of the PathHelperUtil class to manage and retrieve navigation paths.

Methods

  • registerPath(key: string, pathFunction: PathFunction, label: string, navs: string[], group?: string): void

    Registers a new path.

  • extractNavLinks(navName: string): NavLink[]

    Extracts paths that belong to a specified navigation name.

  • extractGroupPaths(groupName: string): NavLink[]

    Extracts paths that belong to a specified group name.

  • getPath(key: string): NavLink | undefined

    Retrieves the path object for the specified key.

  • getPaths(): Paths

    Retrieves a copy of the paths object.

Usage Examples

Registering a Path

To register a new path, use the registerPath method.

This method has the following signature:

registerPath(key: string, pathFunction: PathFunction, label: string, navs: string[], group?: string): void

  • key is your identifier within the paths object that this utility uses to manage your paths. You can use it to get the path later using getPath('key').
  • pathFunction is a callback that returns the path. This can accept data for dynamic routes.
  • label is the text that you can use in your links later.
  • navs accepts string[]. These are the names of your navigations such as mainNav, sidebar, etc., You can use these navigation names in extractNavLinks() to create an array of path to create your nav list.
  • group? is optional, but is used to categorise your paths. For example you may have /blog, /blog/[id], /blog/new. The group allows you to get a list of paths within this group category using extractGroupPaths().

Setting descriptive navigation lists and groups can help to create navigation lists using the extractNavLinks and extractGroupPaths methods.

import { pathHelper } from "path-helper-util";

// static path
pathHelper.registerPath("home", () => "/", "Home", ["main"]);

// dynamic
pathHelper.registerPath(
  "profile",
  (userId: string) => `/user/${userId}`,
  "Profile",
  ["main"],
  "user"
);

When registering your paths we need to ensure the registerPath calls are executed.

We have a few ways to do this:

Register Calls in the root Layout.tsx

export default function Layout({ children }) {
  pathHelper.registerPath("home", () => "/", "Home", ["main"]);
  // ...
}

Dynamically Import a Registrations File

We can also create a new path registration file, such as lib/path-registration.ts. We put all of our registerPath calls in there, and then dynamically import it.

// lib/paths-registration.tsx
import { pathHelper } from "path-helper-util";

pathHelper.registerPath("home", () => "/", "Home", ["main"]);
// ...

// layout.tsx
// note: the layout must be async.
export default async function Layout({ children }) {
  await import("@/lib/path-registration")
    .then(() => {
      console.log("Path registrations have been loaded.");
      console.log("Registered paths:", pathHelper.getPaths());
    })
    .catch((error) => {
      console.error("Error loading path registrations:", error);
    });
}

or we can create and call a registration function:

// layout.tsx
async function registerPaths() {
  try {
    await import("@/lib/path-registration");
    console.log("Path registrations have been loaded.");
  } catch (error) {
    console.error("Error loading path registrations:", error);
  }
}

registerPaths().then(() => {
  // Example usage of the pathHelper
  console.log("Registered paths:", pathHelper.getPaths());
});

export default function Layout({ children }) {
  //...
}

Extracting Paths by Navigation Name

To extract paths by a specific navigation name, use the extractNavLinks method. For example:

const mainNavLinks = pathHelper.extractNavLinks("main");
mainNavLinks.map((link) => (
  <li key={link.label}>
    <Link href={link.path()}>{link.label}</Link>
  </li>
));

Extracting Paths by Group Name

To extract paths by a specific group name, use the extractGroupPaths method. For example:

const userPaths = pathHelper.extractGroupPaths("user");
userPaths.map((link) => (
  <li key={link.label}>
    <Link href={link.path()}>{link.label}</Link>
  </li>
));

Retrieving a Single Path

To retrieve a single path by its key, use the getPath method. For example:

const userSettingsPath = pathHelper.getPath("userSettings");

<Link href={userSettingsPath.path()}>{userSettingsPath.label}</Link>;

Retrieving All Paths

To retrieve a copy of the paths object, use the getPaths method. For example:

const allPaths = pathHelper.getPaths();
console.log(allPaths);

License

This module is licensed under the MIT License. See the LICENSE file for more details.