nih-router
v3.1.0
Published
A simple router that's "Not Invented Here"
Downloads
4
Readme
nih-router
The "Not Invented Here" router. Inspired by this article this router's main distinction from the myriad of alternatives is that I started with the example code in the article and made some small tweaks.
Usage
Install it with yarn or npm:
npm i nih-router
Import the only exposed function (
resolve
)Pass it your routes array, a context object (see the linked article), and a source
It will run the
action
method of the matched route and return the result
import resolve from 'nih-router';
import routes from './routes';
resolve(routes, { pathname: '/foo' }, 'server')
.then(([actionResult, metaResult]) => { ... });
Details
If no matching route can be found it will look for an '/error' route. If that is not found it returns a rejected promise with a 404 error.
API
resolve({Array} routes, {Object} context, {String} source)
routes: An array of route objects that have the following properties. The functions here are all allowed to return Promises or synchronous values.
- path: Required: A string or array of strings to match. e.g.
/users/:userid
- action: Required: A function to run when the path is matched. Used for returning content.
- meta: Optional: Another function to run when the path is matched. Used for returning page meta.
- state: Optional: A function to run only on the server before the other functions run. This is used to set any needed global app state before rendering.
- path: Required: A string or array of strings to match. e.g.
context: An object with information about the context of the request. It must have a
pathname
property at minimum, this object is merged with any matched path parameters and passed to the route functions.source: The source of the resolve call. Only
server
changes behavior (callsstate
function on matched route). But, the data is included in the object passed to the functions in a property calledsource
.Returns: A Promise that resolves with a 2 item array (the result of the action function and the result of the meta function in that order), or rejects with an error.
License
The heart of this code is from the article linked above. That appears to be MIT licensed here. My modifications are released under the license found in this repository.