Project Router
Promise based routing for Express apps. There are 2 parts to this library.
- A promises aware
Route
object you can extend - A map function to connect routes and resources to
Route
objects
Motivation
Most request/response cycles of web apps follow the same pattern
- run some code based on a URL
- potentially reject or redirect based on authorization/authentication
- create, read, update, delete data (aka CRUD)
- present data back to the client
I wanted to abstract the logic of mapping paths to files and have ways to hook into the request/response lifecycle as needed. Instead of having controller objects that manage a group of URLs I found it clearer (and easier to test) to have one object per URL (i.e. UsersShowRoute
). If no route object exists it will render the corresponding view. If one does exists it will process the request by stepping through the lifecycle hooks. This lets you add logic to just one part of the request/response process.
Install
npm install --save project-router
Basic Example
app.js
var app = ;var projectRouter = ; // Map paths to route objects// returns an instance of `express.Router()`var router = projectRouter; app;
app/routes/pages/index.js
var Route = Route; // Extend from the base `Route` objectvar PagesIndexRoute = Route; moduleexports = PagesIndexRoute;
app/views/pages/index.hbs
The data return (or resolved) from the model hook is now available in the view. {{username}}
Seeing the routes
Use Project Router Viewer to see a list of routes.
Extending the Route object
Route objects are what handle incoming requests. There are a few request/response lifecycle hooks you can define. This pattern was heavily inspired by the Ember Router.
Basic lifecycle hooks
The following are the most useful lifecycle hooks listing in the order they are called. beforeModel
, model
, and afterModel
can optionally return promises. These promises will be resolved before calling the next lifecycle method.
.enter()
The first method that gets called. This is your chance to do somehting synchronous (i.e. reject the request based on data already available).
.beforeModel()
If you return a promise from this method it will be resolved before the model
hook gets called. Useful if you have data you need to load asynchronously before getting the model'.
.model()
Should return the data for the route or a promise that resolves to the data.
.afterModel(resolvedModel)
Get passed the result of model
. Use this for any logic that depends on having the data (like authorization that can only be determined with the object). This can also return a promise.
.responseData(resolvedModel)
Also gets passed the result of model
. This just returns resolvedModel
but can be used to transform the repsonse data (serializing, presenting, etc.)
.error(reason)
Catches any promise errors. Calls this.reject(reason)
by default.
Methods
.reject([code,] error)
Ends request with error. Status code defaults to 400
.redirect()
Delegates to Express response redirect
method
.param()
Delegates to Express response param
method
.html(data)
Renders this.templatePath
with data
as context
.json(data)
Sends json response as data
.params()
Returns this.request.params
.body()
Returns this.request.body
.query()
Returns this.request.query
Properties available on route instance
this.request
The Express request object
this.response
The Express response object
this.path
The path defined in router (i.e. '/users/:id')
this.templatePath
The view the route will render. Matches the route filepath by default. this.get('/users, users/index')
will render app/views/users/index.hbs
. You can define this property to change what template will be rendered (i.e. UsersIndexRoute.prototype.templatePath = 'pages/index;
)
this.resource
The resource object (if defined). this.resource('users', {resource: UserModel})
would be UserModel
. This can be defined on the router definition in the options hash or on the Route object (i.e. UsersIndexRoute.prototype.resource = UserModel
).
this.resourceName
The name of the resource (if defined). this.resource('users')
would be users
.
Example Route
var Route = Route; moduleexports = Route;
Defining routes
Define routes by providing a map function to projectRouter.map(fn)
.
this.VERB(path, routeFile)
Maps get
, post
, put
, or delete
to a route file.
projectRouter;
this.resource(name, [options], [fn])
Creates routes for a resource
projectRouter
this.namespace(name, fn)
Creates a namespaced scope for routes
projectRouter;