router.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. /**
  2. * RESTful resource routing middleware for koa.
  3. *
  4. * @author Alex Mingoia <talk@alexmingoia.com>
  5. * @link https://github.com/alexmingoia/koa-router
  6. */
  7. var debug = require('debug')('koa-router');
  8. var compose = require('koa-compose');
  9. var HttpError = require('http-errors');
  10. var methods = require('methods');
  11. var Layer = require('./layer');
  12. /**
  13. * @module koa-router
  14. */
  15. module.exports = Router;
  16. /**
  17. * Create a new router.
  18. *
  19. * @example
  20. *
  21. * Basic usage:
  22. *
  23. * ```javascript
  24. * var Koa = require('koa');
  25. * var Router = require('koa-router');
  26. *
  27. * var app = new Koa();
  28. * var router = new Router();
  29. *
  30. * router.get('/', (ctx, next) => {
  31. * // ctx.router available
  32. * });
  33. *
  34. * app
  35. * .use(router.routes())
  36. * .use(router.allowedMethods());
  37. * ```
  38. *
  39. * @alias module:koa-router
  40. * @param {Object=} opts
  41. * @param {String=} opts.prefix prefix router paths
  42. * @constructor
  43. */
  44. function Router(opts) {
  45. if (!(this instanceof Router)) {
  46. return new Router(opts);
  47. }
  48. this.opts = opts || {};
  49. this.methods = this.opts.methods || [
  50. 'HEAD',
  51. 'OPTIONS',
  52. 'GET',
  53. 'PUT',
  54. 'PATCH',
  55. 'POST',
  56. 'DELETE'
  57. ];
  58. this.params = {};
  59. this.stack = [];
  60. };
  61. /**
  62. * Create `router.verb()` methods, where *verb* is one of the HTTP verbs such
  63. * as `router.get()` or `router.post()`.
  64. *
  65. * Match URL patterns to callback functions or controller actions using `router.verb()`,
  66. * where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()`.
  67. *
  68. * Additionaly, `router.all()` can be used to match against all methods.
  69. *
  70. * ```javascript
  71. * router
  72. * .get('/', (ctx, next) => {
  73. * ctx.body = 'Hello World!';
  74. * })
  75. * .post('/users', (ctx, next) => {
  76. * // ...
  77. * })
  78. * .put('/users/:id', (ctx, next) => {
  79. * // ...
  80. * })
  81. * .del('/users/:id', (ctx, next) => {
  82. * // ...
  83. * })
  84. * .all('/users/:id', (ctx, next) => {
  85. * // ...
  86. * });
  87. * ```
  88. *
  89. * When a route is matched, its path is available at `ctx._matchedRoute` and if named,
  90. * the name is available at `ctx._matchedRouteName`
  91. *
  92. * Route paths will be translated to regular expressions using
  93. * [path-to-regexp](https://github.com/pillarjs/path-to-regexp).
  94. *
  95. * Query strings will not be considered when matching requests.
  96. *
  97. * #### Named routes
  98. *
  99. * Routes can optionally have names. This allows generation of URLs and easy
  100. * renaming of URLs during development.
  101. *
  102. * ```javascript
  103. * router.get('user', '/users/:id', (ctx, next) => {
  104. * // ...
  105. * });
  106. *
  107. * router.url('user', 3);
  108. * // => "/users/3"
  109. * ```
  110. *
  111. * #### Multiple middleware
  112. *
  113. * Multiple middleware may be given:
  114. *
  115. * ```javascript
  116. * router.get(
  117. * '/users/:id',
  118. * (ctx, next) => {
  119. * return User.findOne(ctx.params.id).then(function(user) {
  120. * ctx.user = user;
  121. * next();
  122. * });
  123. * },
  124. * ctx => {
  125. * console.log(ctx.user);
  126. * // => { id: 17, name: "Alex" }
  127. * }
  128. * );
  129. * ```
  130. *
  131. * ### Nested routers
  132. *
  133. * Nesting routers is supported:
  134. *
  135. * ```javascript
  136. * var forums = new Router();
  137. * var posts = new Router();
  138. *
  139. * posts.get('/', (ctx, next) => {...});
  140. * posts.get('/:pid', (ctx, next) => {...});
  141. * forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());
  142. *
  143. * // responds to "/forums/123/posts" and "/forums/123/posts/123"
  144. * app.use(forums.routes());
  145. * ```
  146. *
  147. * #### Router prefixes
  148. *
  149. * Route paths can be prefixed at the router level:
  150. *
  151. * ```javascript
  152. * var router = new Router({
  153. * prefix: '/users'
  154. * });
  155. *
  156. * router.get('/', ...); // responds to "/users"
  157. * router.get('/:id', ...); // responds to "/users/:id"
  158. * ```
  159. *
  160. * #### URL parameters
  161. *
  162. * Named route parameters are captured and added to `ctx.params`.
  163. *
  164. * ```javascript
  165. * router.get('/:category/:title', (ctx, next) => {
  166. * console.log(ctx.params);
  167. * // => { category: 'programming', title: 'how-to-node' }
  168. * });
  169. * ```
  170. *
  171. * The [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module is
  172. * used to convert paths to regular expressions.
  173. *
  174. * @name get|put|post|patch|delete|del
  175. * @memberof module:koa-router.prototype
  176. * @param {String} path
  177. * @param {Function=} middleware route middleware(s)
  178. * @param {Function} callback route callback
  179. * @returns {Router}
  180. */
  181. methods.forEach(function (method) {
  182. Router.prototype[method] = function (name, path, middleware) {
  183. var middleware;
  184. if (typeof path === 'string' || path instanceof RegExp) {
  185. middleware = Array.prototype.slice.call(arguments, 2);
  186. } else {
  187. middleware = Array.prototype.slice.call(arguments, 1);
  188. path = name;
  189. name = null;
  190. }
  191. this.register(path, [method], middleware, {
  192. name: name
  193. });
  194. return this;
  195. };
  196. });
  197. // Alias for `router.delete()` because delete is a reserved word
  198. Router.prototype.del = Router.prototype['delete'];
  199. /**
  200. * Use given middleware.
  201. *
  202. * Middleware run in the order they are defined by `.use()`. They are invoked
  203. * sequentially, requests start at the first middleware and work their way
  204. * "down" the middleware stack.
  205. *
  206. * @example
  207. *
  208. * ```javascript
  209. * // session middleware will run before authorize
  210. * router
  211. * .use(session())
  212. * .use(authorize());
  213. *
  214. * // use middleware only with given path
  215. * router.use('/users', userAuth());
  216. *
  217. * // or with an array of paths
  218. * router.use(['/users', '/admin'], userAuth());
  219. *
  220. * app.use(router.routes());
  221. * ```
  222. *
  223. * @param {String=} path
  224. * @param {Function} middleware
  225. * @param {Function=} ...
  226. * @returns {Router}
  227. */
  228. Router.prototype.use = function () {
  229. var router = this;
  230. var middleware = Array.prototype.slice.call(arguments);
  231. var path;
  232. // support array of paths
  233. if (Array.isArray(middleware[0]) && typeof middleware[0][0] === 'string') {
  234. middleware[0].forEach(function (p) {
  235. router.use.apply(router, [p].concat(middleware.slice(1)));
  236. });
  237. return this;
  238. }
  239. var hasPath = typeof middleware[0] === 'string';
  240. if (hasPath) {
  241. path = middleware.shift();
  242. }
  243. middleware.forEach(function (m) {
  244. if (m.router) {
  245. m.router.stack.forEach(function (nestedLayer) {
  246. if (path) nestedLayer.setPrefix(path);
  247. if (router.opts.prefix) nestedLayer.setPrefix(router.opts.prefix);
  248. router.stack.push(nestedLayer);
  249. });
  250. if (router.params) {
  251. Object.keys(router.params).forEach(function (key) {
  252. m.router.param(key, router.params[key]);
  253. });
  254. }
  255. } else {
  256. router.register(path || '(.*)', [], m, { end: false, ignoreCaptures: !hasPath });
  257. }
  258. });
  259. return this;
  260. };
  261. /**
  262. * Set the path prefix for a Router instance that was already initialized.
  263. *
  264. * @example
  265. *
  266. * ```javascript
  267. * router.prefix('/things/:thing_id')
  268. * ```
  269. *
  270. * @param {String} prefix
  271. * @returns {Router}
  272. */
  273. Router.prototype.prefix = function (prefix) {
  274. prefix = prefix.replace(/\/$/, '');
  275. this.opts.prefix = prefix;
  276. this.stack.forEach(function (route) {
  277. route.setPrefix(prefix);
  278. });
  279. return this;
  280. };
  281. /**
  282. * Returns router middleware which dispatches a route matching the request.
  283. *
  284. * @returns {Function}
  285. */
  286. Router.prototype.routes = Router.prototype.middleware = function () {
  287. var router = this;
  288. var dispatch = function dispatch(ctx, next) {
  289. debug('%s %s', ctx.method, ctx.path);
  290. var path = router.opts.routerPath || ctx.routerPath || ctx.path;
  291. var matched = router.match(path, ctx.method);
  292. var layerChain, layer, i;
  293. if (ctx.matched) {
  294. ctx.matched.push.apply(ctx.matched, matched.path);
  295. } else {
  296. ctx.matched = matched.path;
  297. }
  298. ctx.router = router;
  299. if (!matched.route) return next();
  300. var matchedLayers = matched.pathAndMethod
  301. var mostSpecificLayer = matchedLayers[matchedLayers.length - 1]
  302. ctx._matchedRoute = mostSpecificLayer.path;
  303. if (mostSpecificLayer.name) {
  304. ctx._matchedRouteName = mostSpecificLayer.name;
  305. }
  306. layerChain = matchedLayers.reduce(function(memo, layer) {
  307. memo.push(function(ctx, next) {
  308. ctx.captures = layer.captures(path, ctx.captures);
  309. ctx.params = layer.params(path, ctx.captures, ctx.params);
  310. ctx.routerName = layer.name;
  311. return next();
  312. });
  313. return memo.concat(layer.stack);
  314. }, []);
  315. return compose(layerChain)(ctx, next);
  316. };
  317. dispatch.router = this;
  318. return dispatch;
  319. };
  320. /**
  321. * Returns separate middleware for responding to `OPTIONS` requests with
  322. * an `Allow` header containing the allowed methods, as well as responding
  323. * with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
  324. *
  325. * @example
  326. *
  327. * ```javascript
  328. * var Koa = require('koa');
  329. * var Router = require('koa-router');
  330. *
  331. * var app = new Koa();
  332. * var router = new Router();
  333. *
  334. * app.use(router.routes());
  335. * app.use(router.allowedMethods());
  336. * ```
  337. *
  338. * **Example with [Boom](https://github.com/hapijs/boom)**
  339. *
  340. * ```javascript
  341. * var Koa = require('koa');
  342. * var Router = require('koa-router');
  343. * var Boom = require('boom');
  344. *
  345. * var app = new Koa();
  346. * var router = new Router();
  347. *
  348. * app.use(router.routes());
  349. * app.use(router.allowedMethods({
  350. * throw: true,
  351. * notImplemented: () => new Boom.notImplemented(),
  352. * methodNotAllowed: () => new Boom.methodNotAllowed()
  353. * }));
  354. * ```
  355. *
  356. * @param {Object=} options
  357. * @param {Boolean=} options.throw throw error instead of setting status and header
  358. * @param {Function=} options.notImplemented throw the returned value in place of the default NotImplemented error
  359. * @param {Function=} options.methodNotAllowed throw the returned value in place of the default MethodNotAllowed error
  360. * @returns {Function}
  361. */
  362. Router.prototype.allowedMethods = function (options) {
  363. options = options || {};
  364. var implemented = this.methods;
  365. return function allowedMethods(ctx, next) {
  366. return next().then(function() {
  367. var allowed = {};
  368. if (!ctx.status || ctx.status === 404) {
  369. ctx.matched.forEach(function (route) {
  370. route.methods.forEach(function (method) {
  371. allowed[method] = method;
  372. });
  373. });
  374. var allowedArr = Object.keys(allowed);
  375. if (!~implemented.indexOf(ctx.method)) {
  376. if (options.throw) {
  377. var notImplementedThrowable;
  378. if (typeof options.notImplemented === 'function') {
  379. notImplementedThrowable = options.notImplemented(); // set whatever the user returns from their function
  380. } else {
  381. notImplementedThrowable = new HttpError.NotImplemented();
  382. }
  383. throw notImplementedThrowable;
  384. } else {
  385. ctx.status = 501;
  386. ctx.set('Allow', allowedArr.join(', '));
  387. }
  388. } else if (allowedArr.length) {
  389. if (ctx.method === 'OPTIONS') {
  390. ctx.status = 200;
  391. ctx.body = '';
  392. ctx.set('Allow', allowedArr.join(', '));
  393. } else if (!allowed[ctx.method]) {
  394. if (options.throw) {
  395. var notAllowedThrowable;
  396. if (typeof options.methodNotAllowed === 'function') {
  397. notAllowedThrowable = options.methodNotAllowed(); // set whatever the user returns from their function
  398. } else {
  399. notAllowedThrowable = new HttpError.MethodNotAllowed();
  400. }
  401. throw notAllowedThrowable;
  402. } else {
  403. ctx.status = 405;
  404. ctx.set('Allow', allowedArr.join(', '));
  405. }
  406. }
  407. }
  408. }
  409. });
  410. };
  411. };
  412. /**
  413. * Register route with all methods.
  414. *
  415. * @param {String} name Optional.
  416. * @param {String} path
  417. * @param {Function=} middleware You may also pass multiple middleware.
  418. * @param {Function} callback
  419. * @returns {Router}
  420. * @private
  421. */
  422. Router.prototype.all = function (name, path, middleware) {
  423. var middleware;
  424. if (typeof path === 'string') {
  425. middleware = Array.prototype.slice.call(arguments, 2);
  426. } else {
  427. middleware = Array.prototype.slice.call(arguments, 1);
  428. path = name;
  429. name = null;
  430. }
  431. this.register(path, methods, middleware, {
  432. name: name
  433. });
  434. return this;
  435. };
  436. /**
  437. * Redirect `source` to `destination` URL with optional 30x status `code`.
  438. *
  439. * Both `source` and `destination` can be route names.
  440. *
  441. * ```javascript
  442. * router.redirect('/login', 'sign-in');
  443. * ```
  444. *
  445. * This is equivalent to:
  446. *
  447. * ```javascript
  448. * router.all('/login', ctx => {
  449. * ctx.redirect('/sign-in');
  450. * ctx.status = 301;
  451. * });
  452. * ```
  453. *
  454. * @param {String} source URL or route name.
  455. * @param {String} destination URL or route name.
  456. * @param {Number=} code HTTP status code (default: 301).
  457. * @returns {Router}
  458. */
  459. Router.prototype.redirect = function (source, destination, code) {
  460. // lookup source route by name
  461. if (source[0] !== '/') {
  462. source = this.url(source);
  463. }
  464. // lookup destination route by name
  465. if (destination[0] !== '/') {
  466. destination = this.url(destination);
  467. }
  468. return this.all(source, ctx => {
  469. ctx.redirect(destination);
  470. ctx.status = code || 301;
  471. });
  472. };
  473. /**
  474. * Create and register a route.
  475. *
  476. * @param {String} path Path string.
  477. * @param {Array.<String>} methods Array of HTTP verbs.
  478. * @param {Function} middleware Multiple middleware also accepted.
  479. * @returns {Layer}
  480. * @private
  481. */
  482. Router.prototype.register = function (path, methods, middleware, opts) {
  483. opts = opts || {};
  484. var router = this;
  485. var stack = this.stack;
  486. // support array of paths
  487. if (Array.isArray(path)) {
  488. path.forEach(function (p) {
  489. router.register.call(router, p, methods, middleware, opts);
  490. });
  491. return this;
  492. }
  493. // create route
  494. var route = new Layer(path, methods, middleware, {
  495. end: opts.end === false ? opts.end : true,
  496. name: opts.name,
  497. sensitive: opts.sensitive || this.opts.sensitive || false,
  498. strict: opts.strict || this.opts.strict || false,
  499. prefix: opts.prefix || this.opts.prefix || "",
  500. ignoreCaptures: opts.ignoreCaptures
  501. });
  502. if (this.opts.prefix) {
  503. route.setPrefix(this.opts.prefix);
  504. }
  505. // add parameter middleware
  506. Object.keys(this.params).forEach(function (param) {
  507. route.param(param, this.params[param]);
  508. }, this);
  509. stack.push(route);
  510. return route;
  511. };
  512. /**
  513. * Lookup route with given `name`.
  514. *
  515. * @param {String} name
  516. * @returns {Layer|false}
  517. */
  518. Router.prototype.route = function (name) {
  519. var routes = this.stack;
  520. for (var len = routes.length, i=0; i<len; i++) {
  521. if (routes[i].name && routes[i].name === name) {
  522. return routes[i];
  523. }
  524. }
  525. return false;
  526. };
  527. /**
  528. * Generate URL for route. Takes a route name and map of named `params`.
  529. *
  530. * @example
  531. *
  532. * ```javascript
  533. * router.get('user', '/users/:id', (ctx, next) => {
  534. * // ...
  535. * });
  536. *
  537. * router.url('user', 3);
  538. * // => "/users/3"
  539. *
  540. * router.url('user', { id: 3 });
  541. * // => "/users/3"
  542. *
  543. * router.use((ctx, next) => {
  544. * // redirect to named route
  545. * ctx.redirect(ctx.router.url('sign-in'));
  546. * })
  547. *
  548. * router.url('user', { id: 3 }, { query: { limit: 1 } });
  549. * // => "/users/3?limit=1"
  550. *
  551. * router.url('user', { id: 3 }, { query: "limit=1" });
  552. * // => "/users/3?limit=1"
  553. * ```
  554. *
  555. * @param {String} name route name
  556. * @param {Object} params url parameters
  557. * @param {Object} [options] options parameter
  558. * @param {Object|String} [options.query] query options
  559. * @returns {String|Error}
  560. */
  561. Router.prototype.url = function (name, params) {
  562. var route = this.route(name);
  563. if (route) {
  564. var args = Array.prototype.slice.call(arguments, 1);
  565. return route.url.apply(route, args);
  566. }
  567. return new Error("No route found for name: " + name);
  568. };
  569. /**
  570. * Match given `path` and return corresponding routes.
  571. *
  572. * @param {String} path
  573. * @param {String} method
  574. * @returns {Object.<path, pathAndMethod>} returns layers that matched path and
  575. * path and method.
  576. * @private
  577. */
  578. Router.prototype.match = function (path, method) {
  579. var layers = this.stack;
  580. var layer;
  581. var matched = {
  582. path: [],
  583. pathAndMethod: [],
  584. route: false
  585. };
  586. for (var len = layers.length, i = 0; i < len; i++) {
  587. layer = layers[i];
  588. debug('test %s %s', layer.path, layer.regexp);
  589. if (layer.match(path)) {
  590. matched.path.push(layer);
  591. if (layer.methods.length === 0 || ~layer.methods.indexOf(method)) {
  592. matched.pathAndMethod.push(layer);
  593. if (layer.methods.length) matched.route = true;
  594. }
  595. }
  596. }
  597. return matched;
  598. };
  599. /**
  600. * Run middleware for named route parameters. Useful for auto-loading or
  601. * validation.
  602. *
  603. * @example
  604. *
  605. * ```javascript
  606. * router
  607. * .param('user', (id, ctx, next) => {
  608. * ctx.user = users[id];
  609. * if (!ctx.user) return ctx.status = 404;
  610. * return next();
  611. * })
  612. * .get('/users/:user', ctx => {
  613. * ctx.body = ctx.user;
  614. * })
  615. * .get('/users/:user/friends', ctx => {
  616. * return ctx.user.getFriends().then(function(friends) {
  617. * ctx.body = friends;
  618. * });
  619. * })
  620. * // /users/3 => {"id": 3, "name": "Alex"}
  621. * // /users/3/friends => [{"id": 4, "name": "TJ"}]
  622. * ```
  623. *
  624. * @param {String} param
  625. * @param {Function} middleware
  626. * @returns {Router}
  627. */
  628. Router.prototype.param = function (param, middleware) {
  629. this.params[param] = middleware;
  630. this.stack.forEach(function (route) {
  631. route.param(param, middleware);
  632. });
  633. return this;
  634. };
  635. /**
  636. * Generate URL from url pattern and given `params`.
  637. *
  638. * @example
  639. *
  640. * ```javascript
  641. * var url = Router.url('/users/:id', {id: 1});
  642. * // => "/users/1"
  643. * ```
  644. *
  645. * @param {String} path url pattern
  646. * @param {Object} params url parameters
  647. * @returns {String}
  648. */
  649. Router.url = function (path, params) {
  650. return Layer.prototype.url.call({path: path}, params);
  651. };