5 var debug = require('debug')('express:router:route');
6 var Layer = require('./layer');
7 var methods = require('methods');
8 var utils = require('../utils');
14 module.exports = Route;
17 * Initialize `Route` with the given `path`,
19 * @param {String} path
23 function Route(path) {
24 debug('new %s', path);
28 // route handlers for various http methods
36 Route.prototype._handles_method = function _handles_method(method) {
37 if (this.methods._all) {
41 method = method.toLowerCase();
43 if (method === 'head' && !this.methods['head']) {
47 return Boolean(this.methods[method]);
51 * @return {Array} supported HTTP methods
55 Route.prototype._options = function _options() {
56 var methods = Object.keys(this.methods);
58 // append automatic head
59 if (this.methods.get && !this.methods.head) {
63 for (var i = 0; i < methods.length; i++) {
65 methods[i] = methods[i].toUpperCase();
72 * dispatch req, res into this route
77 Route.prototype.dispatch = function(req, res, done){
79 var stack = this.stack;
80 if (stack.length === 0) {
84 var method = req.method.toLowerCase();
85 if (method === 'head' && !this.methods['head']) {
94 if (err && err === 'route') {
98 var layer = stack[idx++];
103 if (layer.method && layer.method !== method) {
108 layer.handle_error(err, req, res, next);
110 layer.handle_request(req, res, next);
116 * Add a handler for all HTTP verbs to this route.
118 * Behaves just like middleware and can respond or call `next`
119 * to continue processing.
121 * You can use multiple `.all` call to add multiple handlers.
123 * function check_something(req, res, next){
127 * function validate_user(req, res, next){
132 * .all(validate_user)
133 * .all(check_something)
134 * .get(function(req, res, next){
135 * res.send('hello world');
138 * @param {function} handler
139 * @return {Route} for chaining
143 Route.prototype.all = function(){
144 var callbacks = utils.flatten([].slice.call(arguments));
145 callbacks.forEach(function(fn) {
146 if (typeof fn !== 'function') {
147 var type = {}.toString.call(fn);
148 var msg = 'Route.all() requires callback functions but got a ' + type;
149 throw new Error(msg);
152 var layer = Layer('/', {}, fn);
153 layer.method = undefined;
155 this.methods._all = true;
156 this.stack.push(layer);
162 methods.forEach(function(method){
163 Route.prototype[method] = function(){
164 var callbacks = utils.flatten([].slice.call(arguments));
166 callbacks.forEach(function(fn) {
167 if (typeof fn !== 'function') {
168 var type = {}.toString.call(fn);
169 var msg = 'Route.' + method + '() requires callback functions but got a ' + type;
170 throw new Error(msg);
173 debug('%s %s', method, this.path);
175 var layer = Layer('/', {}, fn);
176 layer.method = method;
178 this.methods[method] = true;
179 this.stack.push(layer);