Yet another routing for Express
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib #25 getRoutes() renamed to fetchRoutes() and is now fallback method f… Aug 26, 2016
test
.codeclimate.yml
.editorconfig
.gitignore
.travis.yml
LICENSE
Readme.md
package.json

Readme.md

router-express Version Badge

NPM Downloads Build Status Coverage Status dependency status Code Climate Codacy Badge Join the chat at https://gitter.im/router-express/Lobby

Install

npm install --save router-express

Basic usage

var express = require('express')
var routerExpress = require('router-express')

var app = express()

var routes = [
  {
    name: 'homepage',
    url: '/',
    module: 'static/home'
  },
  {
    name: 'contact',
    url: '/contact-us',
    module: 'static/contact'
  }
]

global.Router = new RouterExpress(routes)
Router.bind(app)

Modules structure

modules/
  static/
    home/
      index.js
    contact/
      index.js

Module file

// modules/static/home/index.js
module.exports = function (req, res) {
  return res.end('Homepage')
}

URL methods

var example = Router.createUrl('contact', {foo: 'bar'}) // -> /contact-us?foo=bar
var another = Router.updateUrlWithParam(example, 'foo', undefined, res.params.route) // -> /contact-us

Advanced usage

Access routes

When you create your new RouterExpress instance, you can access all the routes via

Router.routes

List of route parameters

{
  actionFile: // @alias module
  lastOrder:
  modulesDir: // @default `path.join(__dirname, 'modules')`
  method: // @default 'get'
  module: // @alias actionFile
  name:
  order:
  params: // @default {}
  regexUrl: // @reverts to url
  regexParams:
  url:
}

Fetch route files automatically

Put your routes.json or routes.js files in every folder in your modules folder, then you can fetch all your routes and merge them with

var RouterExpress = require('router-express')

var routes = RouterExpress.fetchRoutes()
// or for your custom modules directory:
var routes = RouterExpress.fetchRoutes('myModules')

Features

  • Get a route by its name (route.name) and access its properties
  • Create a url for a route by its name (route.name) - reverse routing
  • Update a url via providing parameters
  • Inject/update parameters of a url defined in regex (regexUrl, regexParams)
  • Combine all request parameters to res.params container
  • Set default parameter values of res.params by defining them on route.params.
  • Access request's route object in action via res.params.route
  • Middleware function support before route action is called