/** * Dependencies */ var debug = require('debug')('koa-router') , methods = require('methods') , Route = require('./route'); /** * Expose `Router` */ module.exports = Router; /** * Initialize Router. * * @param {Application=} app Optional. Extends app with methods such * as `app.get()`, `app.post()`, etc. * @param {Object=} opts Optional. Passed to `path-to-regexp`. * @return {Router} * @api public */ function Router(app, opts) { if (!(this instanceof Router)) { var router = new Router(app, opts); return router.middleware(); } if (app && !app.use) { opts = app; app = null; } this.opts = opts || {}; this.methods = ['OPTIONS']; this.routes = []; this.params = {}; // extend application if (app) this.extendApp(app); }; /** * Router prototype */ var router = Router.prototype; /** * Router middleware factory. Returns router middleware which dispatches route * middleware corresponding to the request. * * @param {Function} next * @return {Function} * @api public */ router.middleware = function() { var router = this; return function *dispatch(next) { var matchedRoutes; // Parameters for this route if (!(this.params instanceof Array)) { this.params = []; } var pathname = router.opts.routerPath || this.routerPath || this.path; debug('%s %s', this.method, pathname); // Find routes matching requested path if (matchedRoutes = router.match(pathname)) { var methodsAvailable = {}; // Find matched route for requested method for (var len = matchedRoutes.length, i=0; i 0 ? matchedRoutes : false; }; router.param = function(param, fn) { this.params[param] = fn; this.routes.forEach(function(route) { route.param(param, fn); }); return this; }; /** * Extend given `app` with router methods. * * @param {Application} app * @return {Application} * @api private */ router.extendApp = function(app) { var router = this; app.url = router.url.bind(router); app.router = router; ['all', 'redirect', 'register', 'del', 'param'] .concat(methods) .forEach(function(method) { app[method] = function() { router[method].apply(router, arguments); return this; }; }); return app; }; /** * Merge b into a. * * @param {Object} a * @param {Object} b * @return {Object} a * @api private */ function merge(a, b) { if (!b) return a; for (var k in b) a[k] = b[k]; return a; }