{"id":20812302,"url":"https://github.com/ukayani/restify-router","last_synced_at":"2025-05-08T21:20:23.680Z","repository":{"id":3699236,"uuid":"43303600","full_name":"ukayani/restify-router","owner":"ukayani","description":"A router interface for restify that lets you aggregate route definitions and apply to a restify server","archived":false,"fork":false,"pushed_at":"2023-03-04T02:55:43.000Z","size":222,"stargazers_count":52,"open_issues_count":9,"forks_count":15,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-04-26T09:35:03.037Z","etag":null,"topics":["express-router","organization","restify","router","routing"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ukayani.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2015-09-28T13:47:26.000Z","updated_at":"2022-06-15T18:14:44.000Z","dependencies_parsed_at":"2023-07-08T04:31:58.100Z","dependency_job_id":null,"html_url":"https://github.com/ukayani/restify-router","commit_stats":{"total_commits":71,"total_committers":9,"mean_commits":7.888888888888889,"dds":0.5352112676056338,"last_synced_commit":"11c74543453785663c5f440c5d4c1f6f6d21b595"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ukayani%2Frestify-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ukayani%2Frestify-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ukayani%2Frestify-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ukayani%2Frestify-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ukayani","download_url":"https://codeload.github.com/ukayani/restify-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252834311,"owners_count":21811350,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["express-router","organization","restify","router","routing"],"created_at":"2024-11-17T20:52:16.841Z","updated_at":"2025-05-08T21:20:23.602Z","avatar_url":"https://github.com/ukayani.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Restify Router\n\n![Build Status](https://github.com/ukayani/restify-router/workflows/Build/badge.svg?branch=master)\n\nThis module allows you to define your routes using a Router interface that is identical to how routes are registered\non a restify server. You can then apply the routes to a server instance.\n\nBorrowing from the idea of Express router where you can organize routes by creating multiple routers and applying them\nto an express server, this component allows you to achieve a similar separation/grouping of route definitions.\n\n## Summary\n- [Installation](#installation)\n  - [Creating a router](#creating-a-router)\n  - [Why use it?](#why-use-it)\n- [Prefixing Routes](#prefixing-routes)\n- [Nesting Routers](#nesting-routers)\n  - [Example Usage](#example-usage)\n- [Grouping Routers](#grouping-routers)\n  - [Example Usage](#basic-usage)\n  - [Example Usage with middleware](#basic-usage-with-nesting-middlewares)\n- [Common Middleware](#common-middleware)\n\n# Installation\n\n```bash\n$ npm install --save restify-router\n```\n\n## Creating a router\n\nA router object is an isolated instance of routes. The router interface matches the interface for adding routes to a\nrestify server:\n\n```javascript\nvar Router = require('restify-router').Router;\nvar routerInstance = new  Router();\nvar restify = require('restify');\n\nfunction respond(req, res, next) {\n  res.send('hello ' + req.params.name);\n  next();\n}\n\n// add a route like you would on a restify server instance\nrouterInstance.get('/hello/:name', respond);\n\nvar server = restify.createServer();\n// add all routes registered in the router to this server instance\nrouterInstance.applyRoutes(server);\n\nserver.listen(8080, function() {\n  console.log('%s listening at %s', server.name, server.url);\n});\n```\n\n## Why use it?\n\nWhen your application starts to contain a lot of routes, you may want to group the definition of routes in\nseparate files rather than registering every route in a single server bootstrap/creation file.\n\nFor example, if we have two sets of routes in our application:\n\nUsers:\n\n- GET `/users`\n- GET `/users/:id`\n\nPosts:\n\n- GET `/posts`\n- GET `/posts/:id`\n\n```javascript\nvar userRouter = require('./user.router'); // return a Router with only user route definitions\nvar postsRouter = require('./posts.router'); // return a Router with only posts route definitions\n\nvar restify = require('restify');\nvar server = restify.createServer();\n\n// add user routes\nuserRouter.applyRoutes(server);\n\n// add posts routes\npostsRouter.applyRoutes(server);\n\nserver.listen(8080, function() {\n  console.log('%s listening at %s', server.name, server.url);\n});\n```\n\n# Prefixing Routes\n\nTo prefix all routes, specify the prefix as the second argument to `router.applyRoutes(server, prefix)`\n\n- `prefix` must be a string or a regex\n\nExample:\n\nRoutes:\n\n- GET `/admin/settings`\n- GET `/admin/controls`\n\n\n```javascript\nvar Router = require('restify-router').Router;\nvar restify = require('restify');\n\nfunction settings(req, res, next) {\n  res.send('settings');\n  next();\n}\n\nfunction controls(req, res, next) {\n  res.send('controls');\n  next();\n}\n\nvar routerInstance = new Router();\n\n// add a route like you would on a restify server instance\nrouterInstance.get('/settings', settings);\nrouterInstance.get('/controls', controls);\n\nvar server = restify.createServer();\n// add all routes registered in the router to this server instance with uri prefix 'admin'\nrouterInstance.applyRoutes(server, '/admin');\n\nserver.listen(8080, function() {\n  console.log('%s listening at %s', server.name, server.url);\n});\n\n```\n\n# Nesting Routers\n\nIf you are familiar with Express style routers, you have the ability to nest routers under\nother routers to create a hierarchy of route definitions.\n\nTo nest routers use the `.add` method on a Router:\n\n```javascript\nrouter.add(path, router);\n```\n\n- path - a string or regexp path beginning with a forward slash (/)\n    - All routes defined in the provided router will be prefixed with this path during registration\n- router - the router instance to nest\n\n## Example Usage\n\n```javascript\n// routes/v1/auth.js\n\nconst router = new Router();\nrouter.post(\"/register\", function (req, res, next) {\n // do something with req.body\n res.send({status: 'success'});\n return next();\n});\n\nmodule.exports = router;\n```\n\n```javascript\n// routes/v1/routes.js\n\nconst router = new Router();\nrouter.add(\"/auth\", require(\"./auth\"));\n\nmodule.exports = router;\n```\n\n```javascript\n// routes/routes.js\n\nconst router = new Router();\nrouter.add(\"/v1\", require(\"./v1/routes\"));\n\nmodule.exports = router;\n```\n\nWith the above router definition from `routes/routes.js` we can do the following call:\n\n`POST /v1/auth/register`\n\nThis call is possible because we have nested routers two levels deep from the `/v1` path.\n\n\n# Grouping Routers\n\nAs an alternative to Nesting Routers, you can use the group to clarify the middlewares manipulation and the routes / files organization.\nWorks in a way that does not need to create multiple instances of the Router like Nesting.\n\nTo group routers use the `.group` method on a Router:\n\n```javascript\nrouter.group(path, callback);\n```\n\n## Example Usage\n\n### Basic Usage\n\n```javascript\nvar Router = require('restify-router').Router;\nvar restify = require('restify');\n\nvar routerInstance = new  Router();\nvar server = restify.createServer();\n\nrouterInstance.get('/', function (req, res, next) {\n  res.send({message: 'home'});\n  return next();\n});\n\nrouterInstance.group('/v1', function (router) {\n  router.get('/', function (req, res, next) {\n    res.send({message: 'home V1'});\n    return next();\n  });\n\n  router.group('/auth', function (router) {\n    router.post('/register', function (req, res, next) {\n      res.send({message: 'success (v1)'});\n      return next();\n    });\n  });\n});\n\nrouterInstance.group('/v2', function (router) {\n  router.get('/', function (req, res, next) {\n    res.send({message: 'home V2'});\n    return next();\n  });\n});\n\n// add all routes registered in the router to this server instance\nrouterInstance.applyRoutes(server);\n\nserver.listen(8081, function() {\n  console.log('%s listening at %s', server.name, server.url);\n});\n```\n\nWith the above code definition we can do the following calls:\n\n- GET `/`\n- GET `/v1`\n- POST `/v1/auth/register`\n- GET `/v2`\n\n### Basic Usage with nesting Middlewares\n\n```javascript\nvar Router = require('restify-router').Router;\nvar restify = require('restify');\n\nvar routerInstance = new  Router();\nvar server = restify.createServer();\n\nfunction midFirst(req, res, next) { /**/ }\nfunction midSecond(req, res, next) { /**/ }\nfunction midThird(req, res, next) { /**/ }\n\nrouterInstance.group('/v1', midFirst, function (router) {\n  router.get('/', function (req, res, next) {\n    res.send({message: 'home V1'});\n    return next();\n  });\n\n  router.group('/auth', midSecond, function (router) {\n    router.post('/register', midThird, function (req, res, next) {\n      res.send({message: 'success (v1)'});\n      return next();\n    });\n  });\n});\n\n// add all routes registered in the router to this server instance\nrouterInstance.applyRoutes(server);\n\nserver.listen(8081, function() {\n  console.log('%s listening at %s', server.name, server.url);\n});\n```\n\nWith the above code definition we can do the following calls:\n\n- GET `/v1 [midFirst]`\n- POST `/v1/auth/register [midFirst, midSecond, midThird]`\n\n# Common Middleware\n\nThere may be times when you want to apply some common middleware to all routes registered with a router.\nFor example, you may want some common authorization middleware for all routes under a specific router.\n\nAll middleware registered via `.use` will be applied before route level middleware.\n\nTo stay consistent with the `restify` server interface, the method on the Router is:\n\n- `.use(middlewareFn, middlewareFn2, ...)`\n- `.use([middlewareFn, middlewareFn2, ...])`\n\n**Note**: Multiple calls to `.use` will result in aggregation of middleware, each successive call will append to the list of common middleware\n\n## Example Usage\n\n```javascript\nvar router = new Router();\n\n// this will run before every route on this router\nrouter.use(function (req, res, next) {\n   if (req.query.role === 'admin') {\n    return next();\n   } else {\n    return next(new errors.UnauthorizedError());\n   }\n});\n\nrouter.get('/hello', function (req, res, next) {\n   res.send('Hello');\n   next();\n});\n\nrouter.get('/test', function (req, res, next) {\n   res.send('Test');\n   next();\n});\n\nrouter.applyRoutes(server);\n\n// calling GET /hello  runs use middle ware first and then the routes middleware\n\n```\n\n# Links\n\nFor more information about Restify Router see [Organizing Restify Routes with Restify Router](http://recursivethoughts.com/organizing-restify-routes-with-restify-router/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fukayani%2Frestify-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fukayani%2Frestify-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fukayani%2Frestify-router/lists"}