Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Last active July 16, 2016 12:52
Show Gist options
  • Save bouzuya/20dffb93201e00507dcdd0fde6de3a0f to your computer and use it in GitHub Desktop.
Save bouzuya/20dffb93201e00507dcdd0fde6de3a0f to your computer and use it in GitHub Desktop.
simple router

simple-router-b

A simple router.

Concept

  • path -> name + params
  • name + params -> path

Usage

$ npm install simple-router-b
import makeRouter from 'simple-router-b';

const config = [
  { name: 'users', template: '/users' },
  { name: 'user', template: '/users/:id' },
  { name: 'roles', template: '/roles/:id' }
];

const router = makeRouter(config);

const route = router.route('/users/123');
assert.deepEqual(route, { name: 'user', params: { id: '123' } });

const unknownRoute = router.route('/unknown');
assert(typeof unknownRoute === 'undefined');

const path = router.path('user', { id: '123' });
assert(path === '/users/123');

const unknownPath = router.path('unknown', { id: '123' });
assert(typeof unknownPath === 'undefined');

Types

type Name = string;
type Path = string;
type Params = { [key: string]: string; };
type Route = { name: Name; params: Params; };
type Router = {
  route: (path: Path) => Route;
  path: (name: Name, params?: Params) => Path;
};
type RouterConfig = { name: Name; template: Template; }[];
type Template = string;
type init = (config: RouterConfig) => Router;

export default init;
@bouzuya
Copy link
Author

bouzuya commented Jul 16, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment