Git Product home page Git Product logo

route-descriptor's Introduction

route-descriptor

Made in Ukraine Build Coverage Version Downloads Discord Donate Fuck Russia

๐ŸŸข Project status: active[?]

This package provides the means to statically represent routes, which helps establish a single source of truth for generating links inside an application.

๐Ÿ’ก This library works best with TypeScript.

Install

  • ๐Ÿ“ฆ npm: npm i route-descriptor

Usage

Routes are created by calling the route(...) function with the route's path and a type that encapsulates its parameters. This returns another function which can be further evaluated against a specific set of route parameters to resolve the matching URL.

Describing a static route

Static routes are routes that have no parameters and, as a result, always resolve to the same URL. To create a descriptor for a static route, call route(...) with just the route's path:

import { route } from 'route-descriptor';

const home = route('/home');

const href = home(); // '/home'

Describing a dynamic route

Dynamic routes can resolve to different URLs depending on the specified parameters. In order to create a descriptor for a dynamic route, call route(...) with a path template and a generic argument that defines the parameters it can accept:

import { route } from 'route-descriptor';

interface ProductParams {
  id: number;
}

const product = route<ProductParams>('/products/:id');

const href = product({ id: 3 }); // '/products/3'

To resolve the URL, the descriptor will try to match the parameter names with placeholders in the path template. If some of the parameters don't match with any of the placeholders, they will be added as query parameters instead:

import { route } from 'route-descriptor';

interface ProductParams {
  id: number;
  showComments?: boolean;
}

const product = route<ProductParams>('/products/:id');

const href = product({
  id: 3,
  showComments: true
}); // '/products/3?showComments=true'

Retrieving the original path

Once descriptor is created, it's possible to retrieve its path template by accessing the path field:

import { route } from 'route-descriptor';

const profile = route<ProfileParams>('/profile/:id/:name?');

const path = profile.path; // '/profile/:id/:name?'

Combining with routing libraries

This package can be used in combination with practically any client-side routing library. For example, here is how to integrate it with React Router:

  • ./src/routes.ts:
// This module serves as a single source of truth for routing

import { route } from 'route-descriptor';

interface ProductParams {
  id: number;
  showComments?: boolean;
}

interface ProfileParams {
  id: number;
  name?: string;
}

export default {
  home: route('/home'),
  product: route<ProductParams>('/products/:id'),
  profile: route<ProfileParams>('/profile/:id/:name?')
};
  • ./src/App.tsx:
import { Route, Switch, BrowserRouter, Link } from 'react-router-dom';
import routes from './routes';

function Home() {
  // To resolve route link, pass the parameters that the route expects
  
  return (
    <div>
      <Link to={routes.home()}>Home</Link>
      <Link to={routes.profile({ id: 1, name: 'JohnDoe' })}>My Profile</Link>
      <Link to={routes.product({ id: 3, showComments: true })}>Random Product</Link>
    </div>
  );
}

function Product() {
  /* ... */
}

function Profile() {
  /* ... */
}

export default function App() {
  // We can use the `path` field to retrieve the original
  // path template and feed it to react-router.

  return (
    <BrowserRouter>
      <Switch>
        <Route path={routes.profile.path} component={Profile} />
        <Route path={routes.product.path} component={Product} />
        <Route path={routes.home.path} component={Home} />
      </Switch>
    </BrowserRouter>
  );
}

Static validation via TypeScript

This package is most useful when paired with TypeScript, as it provides static validation for parameters. For example, all of the following incorrect usages produce errors during compilation:

import { route } from 'route-descriptor';

const home = route('/home');

home({ id: 5 }); // <- error (static route can't accept parameters)

// ----

interface ProductParams {
  id: number;
  showComments?: boolean;
}

const product = route<ProductParams>('/products/:id');

product(); // <- error (dynamic route requires parameters)
product({ showComments: true }); // <- error (missing 'id')
product({ id: 3, name: 'apple' }); // <- error (unexpected 'name')

route-descriptor's People

Contributors

tyrrrz avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.