项目作者: ukayani

项目描述 :
A router interface for restify that lets you aggregate route definitions and apply to a restify server
高级语言: JavaScript
项目地址: git://github.com/ukayani/restify-router.git
创建时间: 2015-09-28T13:47:26Z
项目社区:https://github.com/ukayani/restify-router

开源协议:MIT License

下载


Restify Router

Build Status

This module allows you to define your routes using a Router interface that is identical to how routes are registered
on a restify server. You can then apply the routes to a server instance.

Borrowing from the idea of Express router where you can organize routes by creating multiple routers and applying them
to an express server, this component allows you to achieve a similar separation/grouping of route definitions.

Summary

Installation

  1. $ npm install --save restify-router

Creating a router

A router object is an isolated instance of routes. The router interface matches the interface for adding routes to a
restify server:

  1. var Router = require('restify-router').Router;
  2. var routerInstance = new Router();
  3. var restify = require('restify');
  4. function respond(req, res, next) {
  5. res.send('hello ' + req.params.name);
  6. next();
  7. }
  8. // add a route like you would on a restify server instance
  9. routerInstance.get('/hello/:name', respond);
  10. var server = restify.createServer();
  11. // add all routes registered in the router to this server instance
  12. routerInstance.applyRoutes(server);
  13. server.listen(8080, function() {
  14. console.log('%s listening at %s', server.name, server.url);
  15. });

Why use it?

When your application starts to contain a lot of routes, you may want to group the definition of routes in
separate files rather than registering every route in a single server bootstrap/creation file.

For example, if we have two sets of routes in our application:

Users:

  • GET /users
  • GET /users/:id

Posts:

  • GET /posts
  • GET /posts/:id
  1. var userRouter = require('./user.router'); // return a Router with only user route definitions
  2. var postsRouter = require('./posts.router'); // return a Router with only posts route definitions
  3. var restify = require('restify');
  4. var server = restify.createServer();
  5. // add user routes
  6. userRouter.applyRoutes(server);
  7. // add posts routes
  8. postsRouter.applyRoutes(server);
  9. server.listen(8080, function() {
  10. console.log('%s listening at %s', server.name, server.url);
  11. });

Prefixing Routes

To prefix all routes, specify the prefix as the second argument to router.applyRoutes(server, prefix)

  • prefix must be a string or a regex

Example:

Routes:

  • GET /admin/settings
  • GET /admin/controls
  1. var Router = require('restify-router').Router;
  2. var restify = require('restify');
  3. function settings(req, res, next) {
  4. res.send('settings');
  5. next();
  6. }
  7. function controls(req, res, next) {
  8. res.send('controls');
  9. next();
  10. }
  11. var routerInstance = new Router();
  12. // add a route like you would on a restify server instance
  13. routerInstance.get('/settings', settings);
  14. routerInstance.get('/controls', controls);
  15. var server = restify.createServer();
  16. // add all routes registered in the router to this server instance with uri prefix 'admin'
  17. routerInstance.applyRoutes(server, '/admin');
  18. server.listen(8080, function() {
  19. console.log('%s listening at %s', server.name, server.url);
  20. });

Nesting Routers

If you are familiar with Express style routers, you have the ability to nest routers under
other routers to create a hierarchy of route definitions.

To nest routers use the .add method on a Router:

  1. router.add(path, router);
  • path - a string or regexp path beginning with a forward slash (/)
    • All routes defined in the provided router will be prefixed with this path during registration
  • router - the router instance to nest

Example Usage

  1. // routes/v1/auth.js
  2. const router = new Router();
  3. router.post("/register", function (req, res, next) {
  4. // do something with req.body
  5. res.send({status: 'success'});
  6. return next();
  7. });
  8. module.exports = router;
  1. // routes/v1/routes.js
  2. const router = new Router();
  3. router.add("/auth", require("./auth"));
  4. module.exports = router;
  1. // routes/routes.js
  2. const router = new Router();
  3. router.add("/v1", require("./v1/routes"));
  4. module.exports = router;

With the above router definition from routes/routes.js we can do the following call:

POST /v1/auth/register

This call is possible because we have nested routers two levels deep from the /v1 path.

Grouping Routers

As an alternative to Nesting Routers, you can use the group to clarify the middlewares manipulation and the routes / files organization.
Works in a way that does not need to create multiple instances of the Router like Nesting.

To group routers use the .group method on a Router:

  1. router.group(path, callback);

Example Usage

Basic Usage

  1. var Router = require('restify-router').Router;
  2. var restify = require('restify');
  3. var routerInstance = new Router();
  4. var server = restify.createServer();
  5. routerInstance.get('/', function (req, res, next) {
  6. res.send({message: 'home'});
  7. return next();
  8. });
  9. routerInstance.group('/v1', function (router) {
  10. router.get('/', function (req, res, next) {
  11. res.send({message: 'home V1'});
  12. return next();
  13. });
  14. router.group('/auth', function (router) {
  15. router.post('/register', function (req, res, next) {
  16. res.send({message: 'success (v1)'});
  17. return next();
  18. });
  19. });
  20. });
  21. routerInstance.group('/v2', function (router) {
  22. router.get('/', function (req, res, next) {
  23. res.send({message: 'home V2'});
  24. return next();
  25. });
  26. });
  27. // add all routes registered in the router to this server instance
  28. routerInstance.applyRoutes(server);
  29. server.listen(8081, function() {
  30. console.log('%s listening at %s', server.name, server.url);
  31. });

With the above code definition we can do the following calls:

  • GET /
  • GET /v1
  • POST /v1/auth/register
  • GET /v2

Basic Usage with nesting Middlewares

  1. var Router = require('restify-router').Router;
  2. var restify = require('restify');
  3. var routerInstance = new Router();
  4. var server = restify.createServer();
  5. function midFirst(req, res, next) { /**/ }
  6. function midSecond(req, res, next) { /**/ }
  7. function midThird(req, res, next) { /**/ }
  8. routerInstance.group('/v1', midFirst, function (router) {
  9. router.get('/', function (req, res, next) {
  10. res.send({message: 'home V1'});
  11. return next();
  12. });
  13. router.group('/auth', midSecond, function (router) {
  14. router.post('/register', midThird, function (req, res, next) {
  15. res.send({message: 'success (v1)'});
  16. return next();
  17. });
  18. });
  19. });
  20. // add all routes registered in the router to this server instance
  21. routerInstance.applyRoutes(server);
  22. server.listen(8081, function() {
  23. console.log('%s listening at %s', server.name, server.url);
  24. });

With the above code definition we can do the following calls:

  • GET /v1 [midFirst]
  • POST /v1/auth/register [midFirst, midSecond, midThird]

Common Middleware

There may be times when you want to apply some common middleware to all routes registered with a router.
For example, you may want some common authorization middleware for all routes under a specific router.

All middleware registered via .use will be applied before route level middleware.

To stay consistent with the restify server interface, the method on the Router is:

  • .use(middlewareFn, middlewareFn2, ...)
  • .use([middlewareFn, middlewareFn2, ...])

Note: Multiple calls to .use will result in aggregation of middleware, each successive call will append to the list of common middleware

Example Usage

  1. var router = new Router();
  2. // this will run before every route on this router
  3. router.use(function (req, res, next) {
  4. if (req.query.role === 'admin') {
  5. return next();
  6. } else {
  7. return next(new errors.UnauthorizedError());
  8. }
  9. });
  10. router.get('/hello', function (req, res, next) {
  11. res.send('Hello');
  12. next();
  13. });
  14. router.get('/test', function (req, res, next) {
  15. res.send('Test');
  16. next();
  17. });
  18. router.applyRoutes(server);
  19. // calling GET /hello runs use middle ware first and then the routes middleware

Links

For more information about Restify Router see Organizing Restify Routes with Restify Router