3.0.1 • Published 3 years ago

nih-router v3.0.1

Weekly downloads
5
License
MIT
Repository
gitlab
Last release
3 years ago

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

  1. Install it with yarn or npm: npm i nih-router

  2. Import the only exposed function (resolve)

  3. Pass it your routes array, a context object (see the linked article), and a source

  4. 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.
  • 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 (calls state function on matched route). But, the data is included in the object passed to the functions in a property called source.

  • 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.

3.0.1

3 years ago

3.0.0

3 years ago

2.1.2

5 years ago

2.1.1

7 years ago

2.1.0

7 years ago

2.0.0

7 years ago

1.0.0

7 years ago