A Better Restify Router
A clean way to organize routes for the restify router
Installation
$ npm i -S restify-better-router
Command not working? Follow this tutorial.
Motivation
This package allows you to define your routes using a Route object, making it very easy to attach routes to your restify server. In larger applications which have many routes organizing routes off of file structure may be more optimal than one large file.
Example
File user.js
const Route = moduleexportsname =
File place.js
const Route = moduleexportsname =
File api.js
const restify = ;const Route = var server = restify // sub routesconst name = const place = var api = server;
Creating a route
A router object is an isolated instance of routes. The router interface matches the interface for adding routes to a restify server:
var Router = Router;var routerInstance = ;var restify = ; { res; ;} // add a route like you would on a restify server instancerouterInstance; var server = restify;// add all routes registered in the router to this server instancerouterInstance; server;
Usage
Upon creating a new route an object can be given as a shortcut to the chainable methods
name: string Given route name version: string|string Version require for route path: string Path for a route method: string GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS handler: Function|Function A handler
If you prefer, fluent methods can be used instead of the object.
Assuming we create a route object like this var r = new Route()
.
One can set path and method using...
r.setPath(path)
Sets the path for route aspath
r.get(path)
Sets GET method, with a specifiedpath
r.post(path)
Sets POST method, with a specifiedpath
r.put(path)
Sets PUT method, with a specifiedpath
r.patch(path)
Sets PATCH method, with a specifiedpath
r.head(path)
Sets HEAD method, with a specifiedpath
r.del(path)
orr.delete(path)
Sets DELETE method, with a specifiedpath
r.opts(path)
orr.options(path)
Sets OPTIONS method, with a specifiedpath
One can modify the route's other attributes using...
r.setName(name)
Given route the namename
r.setVersion(verion)
Sets a route's version toversion
(can be an array of versions)r.addHandler(handler)
Addshandler
as the route's function to the router.addRoute(route)
Adds a child route to be prefixed by this route's pathr.addRoutes(routes)
Adds an array of children routesr.attach(server)
Attachés this route and its children toserver
Attaching routes to a server
Once you have made and grouped your routes, you can attach them to the restify server to become live.
const Route = const restify = var r = name: 'route' method: 'get' { res } var server = restify // r will now be seen by the serverr // start serverserver
Influenced by restify-router.