kruschid / typesafe-routes

Spices up your favorite routing library by adding type safety to plain string-based route definitions.
https://kruschid.github.io/typesafe-routes/
MIT License
102 stars 8 forks source link
express react react-router typesafe-routes typescript

Typesafe Routes

Enhance your preferred routing library by incorporating powerful path generation including:

Example (Default Renderer)

import { createRoutes, int } from "typesafe-routes";

const routes = createRoutes({
  users: {
    path: ["users"],
    children: {
      create: { path: ["create"] }
      edit: { path: ["edit", int("uid")] },
      show: {
        path: ["show", int("uid")],
        children: {
          groups: { path: ["groups", int.optional("gid")] }
        }
      },
    }
  }
});

// absolute paths
routes.users.$render({}); // => "/users"
routes.users.create.$render({}); // => "/users/create"
routes.users.show.$render({path: {uid: 123}}); // => "/users/show/123"

// relative paths ("_" indicates the start segment)
routes._.users.$render({}); // => "users"
routes.users._.create.$render({}); // => "create"
routes.users._.show.$render({path: {uid: 321}}); // => "show/321"

// parse path params
routes.users.show.$parseParams({uid: "42"}); // => {uid: 42}
routes.users.show.$parseParams("/users/show/99"); // => {uid: 99}
routes.users._.show.$parseParams("show/99"); // => {uid: 99}

// create from location string
routes
  .users
  .show
  .$from("/users/show/1", {path: {uid: 11}}) // replaces parameters 
  .groups
  .$render({path: {gid: 2}}); // => "/users/show/11/groups/2"

// templates 
routes.users.show.groups.$template(); // => "/users/show/:uid/groups/:gid?"
routes._.users.show.groups.$template(); // => "users/show/:uid/groups/:gid?"
routes.users._show.groups.$template(); // => "show/:uid/groups/:gid?"

// template examples with a custom renderer
routes.users.show.groups.$template(); // => "users/show/{:uid}/groups/{:gid}"

// array based custom templates:
routes.users.show.$template(); // => ["users", "show", {name: "uid", type: "number"}]

Quick Reference

The complete documentation can be found here.

Installation

Version 12 is currently under development. Please don't use it in production yet. The official release will happen soon. The v10 documentation can be found here.

npm i typesafe-routes@next # or any npm alternative

How to Contribute

Buy Me A Coffee

Roadmap

Docs