1.2.0 • Published 9 years ago

kiss-router v1.2.0

Weekly downloads
5
License
MIT
Repository
github
Last release
9 years ago

KISS Router

KISS router is a really stupid simple 'routing' option for use in javascript apps. It's designed to have a really simple API and to be used with whatever history management system you like.

The api consists of one function: createMatcher, which takes an array of routes, and returns a 'matcher' function that will match a Location object to a route. When a match is found, an object is returned with the route name, the route and query parameters, and any additional keys specified in the route definition.

Here's an example of it in use:

import createMatcher from 'kiss-router';

const matcher = createMatcher([
  { name: 'HOME', path: '/' },
  { name: 'POSTS', path: '/posts' },
  { name: 'NEW_POST', path: '/posts/new' },
  { name: 'POST', path: '/posts/:id' },
  { name: 'SEARCH', path: '/search' }
]);

const match1 = matcher({ pathname: '/posts/123', search: '' });
console.log(match1) // { route: 'POST', params: { id: '123' } }

const match2 = matcher({ pathname: '/posts/new', search: '' });
console.log(match1) // { route: 'NEW_POST', params: {} }

const match1 = matcher({ pathname: '/search', search: '?q=hello' });
console.log(match1) // { route: 'SEARCH', params: { q: 'hello' } }

To actually use this library in an app, it should be subscribed to history changes, and the resulting match should be used to render the corresponding page, like so:

import createBrowserHistory from 'history/createBrowserHistory';
import createMatcher from 'kiss-router';

const history = createBrowserHistory();

const matcher = createMatcher([
  { name: 'HOME', path: '/' },
  { name: 'POSTS', path: '/posts' },
  { name: 'NEW_POST', path: '/posts/new' },
  { name: 'POST', path: '/posts/:id' },
  { name: 'SEARCH', path: '/search' }
]);

const render = (location) => {
  const match = matcher(location);

  if (!match) return render404();

  switch (match.route) {
    case 'HOME': return renderHome();
    case 'POSTS': return renderPosts(match.params.page || 1);
    case 'NEW_POST': return renderNewPost();
    case 'POST': return renderPost(match.params.id);
    case 'SEARCH': return renderSearch(match.params.q);
  };
}

history.listen((location) => {
  render(location);
})