Skip to content
Myr

Moved router over from connect

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent 658e064 · Browse files · 3 files+399 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+399 added−1 removed

  • other:+399 added−1 removed

3 files+399 added−1 removed

added:lib/router.js+378 added
12/*!3 * Express - router4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var utils = require('./utils')13 , parse = require('url').parse;1415/**16 * Expose router.17 */1819exports = module.exports = router;2021/**22 * Supported HTTP / WebDAV methods.23 */2425var _methods = exports.methods = [26 'get'27 , 'post'28 , 'put'29 , 'delete'30 , 'connect'31 , 'options'32 , 'trace'33 , 'copy'34 , 'lock'35 , 'mkcol'36 , 'move'37 , 'propfind'38 , 'proppatch'39 , 'unlock'40 , 'report'41 , 'mkactivity'42 , 'checkout'43 , 'merge'44];4546/**47 * Provides Sinatra and Express-like routing capabilities.48 *49 * Examples:50 *51 * connect.router(function(app){52 * app.get('/user/:id', function(req, res, next){53 * // populates req.params.id54 * });55 * app.put('/user/:id', function(req, res, next){56 * // populates req.params.id57 * });58 * })59 *60 * @param {Function} fn61 * @return {Function}62 * @api public63 */6465function router(fn){66 var self = this67 , methods = {}68 , routes = {}69 , params = {};7071 if (!fn) throw new Error('router provider requires a callback function');7273 // Generate method functions74 _methods.forEach(function(method){75 methods[method] = generateMethodFunction(method.toUpperCase());76 });7778 // Alias del -> delete79 methods.del = methods.delete;8081 // Apply callback to all methods82 methods.all = function(){83 var args = arguments;84 _methods.forEach(function(name){85 methods[name].apply(this, args);86 });87 return self;88 };8990 // Register param callback91 methods.param = function(name, fn){92 params[name] = fn;93 };94 95 fn.call(this, methods);9697 function generateMethodFunction(name) {98 var localRoutes = routes[name] = routes[name] || [];99 return function(path, fn){100 var keys = []101 , middleware = [];102103 // slice middleware104 if (arguments.length > 2) {105 middleware = Array.prototype.slice.call(arguments, 1, arguments.length);106 fn = middleware.pop();107 middleware = utils.flatten(middleware);108 }109110 fn.middleware = middleware;111112 if (!path) throw new Error(name + ' route requires a path');113 if (!fn) throw new Error(name + ' route ' + path + ' requires a callback');114 var regexp = path instanceof RegExp115 ? path116 : normalizePath(path, keys);117 localRoutes.push({118 fn: fn119 , path: regexp120 , keys: keys121 , orig: path122 , method: name123 });124 return self;125 };126 }127128 function router(req, res, next){129 var route130 , self = this;131132 (function pass(i){133 if (route = match(req, routes, i)) {134 var i = 0135 , keys = route.keys;136137 req.params = route.params;138139 // Param preconditions140 (function param(err) {141 try {142 var key = keys[i++]143 , val = req.params[key]144 , fn = params[key];145146 if ('route' == err) {147 pass(req._route_index + 1);148 // Error149 } else if (err) {150 next(err);151 // Param has callback152 } else if (fn) {153 // Return style154 if (1 == fn.length) {155 req.params[key] = fn(val);156 param();157 // Middleware style158 } else {159 fn(req, res, param, val);160 }161 // Finished processing params162 } else if (!key) {163 // route middleware164 i = 0;165 (function nextMiddleware(err){166 var fn = route.middleware[i++];167 if ('route' == err) {168 pass(req._route_index + 1);169 } else if (err) {170 next(err);171 } else if (fn) {172 fn(req, res, nextMiddleware);173 } else {174 route.call(self, req, res, function(err){175 if (err) {176 next(err);177 } else {178 pass(req._route_index + 1);179 }180 });181 }182 })();183 // More params184 } else {185 param();186 }187 } catch (err) {188 next(err);189 }190 })();191 } else if ('OPTIONS' == req.method) {192 options(req, res, routes);193 } else {194 next();195 }196 })();197 };198199 router.remove = function(path, method){200 var fns = router.lookup(path, method);201 fns.forEach(function(fn){202 routes[fn.method].splice(fn.index, 1);203 });204 };205206 router.lookup = function(path, method, ret){207 ret = ret || [];208209 // method specific lookup210 if (method) {211 method = method.toUpperCase();212 if (routes[method]) {213 routes[method].forEach(function(route, i){214 if (path == route.orig) {215 var fn = route.fn;216 fn.regexp = route.path;217 fn.keys = route.keys;218 fn.path = route.orig;219 fn.method = route.method;220 fn.index = i;221 ret.push(fn);222 }223 });224 }225 // global lookup226 } else {227 _methods.forEach(function(method){228 router.lookup(path, method, ret);229 });230 }231232 return ret;233 };234235 router.match = function(url, method, ret){236 var ret = ret || []237 , i = 0238 , fn239 , req;240241 // method specific matches242 if (method) {243 method = method.toUpperCase();244 req = { url: url, method: method };245 while (fn = match(req, routes, i)) {246 i = req._route_index + 1;247 ret.push(fn);248 } 249 // global matches250 } else {251 _methods.forEach(function(method){252 router.match(url, method, ret);253 });254 }255256 return ret;257 };258259 return router;260}261262/**263 * Respond to OPTIONS.264 *265 * @param {ServerRequest} req266 * @param {ServerResponse} req267 * @param {Array} routes268 * @api private269 */270271function options(req, res, routes) {272 var pathname = parse(req.url).pathname273 , body = optionsFor(pathname, routes).join(',');274 res.writeHead(200, {275 'Content-Length': body.length276 , 'Allow': body277 });278 res.end(body);279}280281/**282 * Return OPTIONS array for the given `path`, matching `routes`.283 *284 * @param {String} path285 * @param {Array} routes286 * @return {Array}287 * @api private288 */289290function optionsFor(path, routes) {291 return _methods.filter(function(method){292 var arr = routes[method.toUpperCase()];293 for (var i = 0, len = arr.length; i < len; ++i) {294 if (arr[i].path.test(path)) return true;295 }296 }).map(function(method){297 return method.toUpperCase();298 });299}300301/**302 * Normalize the given path string,303 * returning a regular expression.304 *305 * An empty array should be passed,306 * which will contain the placeholder307 * key names. For example "/user/:id" will308 * then contain ["id"].309 *310 * @param {String} path311 * @param {Array} keys312 * @return {RegExp}313 * @api private314 */315316function normalizePath(path, keys) {317 path = path318 .concat('/?')319 .replace(/\/\(/g, '(?:/')320 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){321 keys.push(key);322 slash = slash || '';323 return ''324 + (optional ? '' : slash)325 + '(?:'326 + (optional ? slash : '')327 + (format || '') + (capture || '([^/]+?)') + ')'328 + (optional || '');329 })330 .replace(/([\/.])/g, '\\$1')331 .replace(/\*/g, '(.+)');332 return new RegExp('^' + path + '$', 'i');333}334335/**336 * Attempt to match the given request to337 * one of the routes. When successful338 * a route function is returned.339 *340 * @param {ServerRequest} req341 * @param {Object} routes342 * @return {Function}343 * @api private344 */345346function match(req, routes, i) {347 var captures348 , method = req.method349 , i = i || 0;350 if ('HEAD' == method) method = 'GET';351 if (routes = routes[method]) {352 var url = parse(req.url)353 , pathname = url.pathname;354 for (var len = routes.length; i < len; ++i) {355 var route = routes[i]356 , fn = route.fn357 , path = route.path358 , keys = fn.keys = route.keys;359 if (captures = path.exec(pathname)) {360 fn.method = method;361 fn.params = [];362 for (var j = 1, len = captures.length; j < len; ++j) {363 var key = keys[j-1],364 val = typeof captures[j] === 'string'365 ? decodeURIComponent(captures[j])366 : captures[j];367 if (key) {368 fn.params[key] = val;369 } else {370 fn.params.push(val);371 }372 }373 req._route_index = i;374 return fn;375 }376 }377 }378}
modified:lib/utils.js+21 added
modified:History.md-1 removed
11 unmodified lines
12Closes #63813 * Fixed partial lookup precedence. Closes #63114Shaw]1516162.2.2 / 2011-04-12 17==================1819 * Added second callback support for `res.download()` connection errors
583 unmodified lines