Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Last active Jul 16, 2016
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@bouzuya bouzuya commented Jul 16, 2016

method support

const config = [
  { name: 'users#index', method: 'GET', path: '/users' },
  { name: 'users#create', method: 'POST', path: '/users' },
  { name: 'users#show', method: 'GET', path: '/users/:id' },
  { name: 'users#update', method: 'PATCH', path: '/users/:id' },
  { name: 'users#destroy', method: 'DELETE', path: '/users/:id' }
];

??? name + params -> path (+ method) ???

@bouzuya

This comment has been minimized.

Copy link
Owner Author

@bouzuya bouzuya commented Jul 16, 2016

path != template

@bouzuya

This comment has been minimized.

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