Skip to content

router-creator is a lightweight utility to dynamically build and manage full route definitions, including pathnames, origins, and query or path parameters. It helps you easily construct URLs, inject parameters, and keep route handling consistent across your application.

Notifications You must be signed in to change notification settings

dariel26/router-creator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Router Creator codecov

router-creator is a lightweight TypeScript utility for building full route trees with support for pathnames, nested segments, parameters, attributes, and origins.

It simplifies dynamic URL construction and routing logic in frontend or backend projects, offering utilities to set parameters, resolve full paths or URLs, and even validate if a pathname exists in your route tree.


✨ Features

  • 🌳 Build nested and typed route trees
  • 🌐 Handle full paths and origins
  • βš™οΈ Support for dynamic parameters (e.g. :id)
  • πŸ” Match pathnames and validate against route tree
  • 🏷️ Add attributes to paths (e.g. loggable, authRequired, etc.)
  • πŸ§ͺ Fully tested and TypeScript-ready

πŸ“¦ Installation

npm install router-creator

# or

yarn add router-creator

πŸš€ Getting Started

import RouterCreator, { createRouter } from "router-creator";

// This is the best ".ts way" to get the instance router.
const routes = createRouter("http://localhost:3000", {
    private: {
        users: {
            _att: ["loggable"],
            idUser: ":id_user",
        },
        auth: {
            signout: "sign-out",
            session: {},
        },
    },
    public: {
        auth: {
            signin: "sign-in",
            signup: {
                _path: "sign-up",
                init: {},
                complete: {},
            },
        },
    },
});

// This is a deprecated ".ts way" to get the instance router.
const router = new RouterCreator("http://localhost:3000").createPathnames({
    private: {
        users: {
            _att: ["loggable"],
            idUser: ":id_user",
        },
        auth: {
            signout: "sign-out",
            session: {},
        },
    },
    public: {
        auth: {
            signin: "sign-in",
            signup: {
                _path: "sign-up",
                init: {},
                complete: {},
            },
        },
    },
});

// Accessing full path
router.private.users.root.get(); // "/private/users"
router.private.users.idUser.get(); // "/private/users/:id_user"
router.private.users.idUser.set("123").get(); // "/private/users/123"

//Accessing full URL
router.private.auth.signout.getUrl(); // "http://localhost:3000/private/auth/sign-out"

// Matching pathnames
router.hasPathname("/private/users"); // true
router.hasPathname("/private/users/123"); // true
router.hasPathname("/private/invalid"); // false

// Match path with specific attribute (e.g. "loggable")
router.hasPathname("/private/users/123", { attribute: "loggable" }); // true
router.hasPathname("/private/auth/sign-out", { attribute: "loggable" }); // false

⚠️ WARNING

Create paths that starts with $ or with the reserved names get, set, getParams, getOrigin, etc... May cause unexpected behavior.


πŸ“š API Overview

Defining Your Route Tree with createRouter function

The createRouter() function accepts an origin and plain object that represents your entire route structure. Each key becomes a named path, and you can define dynamic segments, nested paths, and attach custom attributes to each route.


πŸ”‘ Object Syntax

Each key inside the object represents a route segment. You can define:

  • A static path: "segment" that will be converted into "/segment".
  • A dynamic parameter: ":paramName" that will be converted into "/:paramName".
  • Nested objects for nested paths. The key of the object will be used as the path segment if isn't a _path key inside the object.
  • Metadata using special keys:
    • _path: defines the current segment (when isn't defined, the key of the object will be used).
    • _att: an array of custom attributes (optional)

πŸ’‘ Example

const router = createRouter("https://example.com", {
    private: {
        // /private
        users: {
            // /private/users
            idUser: ":idUser", // /private/users/:idUser
        },
        reports: {
            // /reports
            id_report: {
                // /reports/:id_report
                _path: ":id_report",
                _att: ["loggable"],
                download: {
                    // /reports/:id_report/download
                    file: {}, // /reports/:id_report/download/file
                },
            },
        },
    },
});

(DEPRECATED, use createRouter instad) Defining Your Route Tree with createPathnames()

The createPathnames() method accepts a plain object that represents your entire route structure. Each key becomes a named path, and you can define dynamic segments, nested paths, and attach custom attributes to each route.


πŸ”‘ Object Syntax

Each key inside the object represents a route segment. You can define:

  • A static path: "" or "segment" that will be converted into "/" or "/segment" respectively.
  • A dynamic parameter: ":paramName" that will be converted into "/:paramName".
  • Nested objects for nested paths. The key of the object will be used as the path segment if isn't a _path key inside the object.
  • Metadata using special keys:
    • _path: defines the current segment (when isn't defined, the key of the object will be used).
    • _att: an array of custom attributes (optional)

πŸ’‘ Example

const routes = new RouterCreator("https://example.com").createPathnames({
    private: {
        users: {
            idUser: ":idUser",
        },
        reports: {
            id_report: {
                _path: ":id_report",
                _att: ["loggable"],
                download: {
                    file: {},
                },
            },
        },
    },
});

(DEPRECATED, use createRouter instad) new RouterCreator(origin: string)

Creates a new router with a defined base origin (e.g. "https://myapp.com").


Path.get()

Returns the full pathname from the root to this path.

routes.private.users.idUser.get(); // "/private/users/:id_user"

Path.getPath()

Returns the pathname of the current path.

routes.private.users.idUser.getPath(); // "/:id_user"

Path.getUrl()

Returns the full URL including origin.

routes.private.users.idUser.getUrl();
// "http://localhost:3000/private/users/:id_user"

Path.set(value: string)

Injects a parameter into a route that uses a :param placeholder.

routes.private.users.id_user.set("abc123").get(); // "/private/users/abc123"
routes.private.users.id_user.get(); // "/private/users/id-user"

Path.start()

Starts the pathname in the next child path.

routes.private.start().users.id_user.get(); // "/users/:id-user"
routes.private.users.start().id_user.get(); // "/:id-user"

router.hasPathname(pathname: string, options?: { attribute?: string })

Checks if the given pathname exists in the route tree. Optionally filters by attribute.

routes.hasPathname("/private/users/abc123"); // boolean
routes.hasPathname("/private/captures/123/upload/files", { attribute: "loggable" }); // boolean

About

router-creator is a lightweight utility to dynamically build and manage full route definitions, including pathnames, origins, and query or path parameters. It helps you easily construct URLs, inject parameters, and keep route handling consistent across your application.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published