http.js
This file
Path
lib/http.js
572 lines · 11.9 KiB · JavaScript
Last changed by
Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
History of this fileTake it
12/*!3 * Express - HTTPServer4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var qs = require('qs')13 , connect = require('connect')14 , router = require('./router')15 , Router = require('./router')16 , view = require('./view')17 , toArray = require('./utils').toArray18 , methods = router.methods.concat('del', 'all')19 , res = require('./response')20 , url = require('url')21 , utils = connect.utils;2223/**24 * Expose `HTTPServer`.25 */2627exports = module.exports = HTTPServer;2829/**30 * Server proto.31 */3233var app = HTTPServer.prototype;3435/**36 * Initialize a new `HTTPServer` with optional `middleware`.37 *38 * @param {Array} middleware39 * @api public40 */4142function HTTPServer(middleware){43 connect.HTTPServer.call(this, []);44 this.init(middleware);45};4647/**48 * Inherit from `connect.HTTPServer`.49 */5051app.__proto__ = connect.HTTPServer.prototype;5253/**54 * Initialize the server.55 *56 * @param {Array} middleware57 * @api private58 */5960app.init = function(middleware){61 var self = this;62 this.cache = {};63 this.settings = {};64 this.redirects = {};65 this.isCallbacks = {};6667 this.set('home', '/');68 this.set('env', process.env.NODE_ENV || 'development');69 this.use(connect.query());7071 /**72 * Assign several locals with the given `obj`,73 * or return the locals.74 *75 * @param {Object} obj76 * @return {Object|HTTPServer}77 * @api public78 */7980 this.locals = function(obj){81 for (var key in obj) {82 self.locals[key] = obj[key];83 }84 return self;85 };8687 // expose objects to each other88 this.use(function(req, res, next){89 var charset;90 req.query = req.query || {};91 res.setHeader('X-Powered-By', 'Express');92 req.app = res.app = self;93 req.res = res;94 res.req = req;95 req.next = next;9697 // charset98 if (charset = self.set('charset')) res.charset = charset;99100 /**101 * Assign several locals with the given `obj`,102 * or return the locals.103 *104 * @param {Object} obj105 * @return {Object|ServerResponse}106 * @api public107 */108109 res.locals = function(obj){110 for (var key in obj) {111 res.locals[key] = obj[key];112 }113 return res;114 };115116 next();117 });118119 // apply middleware120 if (middleware) middleware.forEach(self.use.bind(self));121122 // router123 this.routes = new Router(this);124 this.__defineGetter__('router', function(){125 this.__usedRouter = true;126 return self.routes.middleware;127 });128129 // default locals130 this.locals.settings = this.settings;131132 // default development configuration133 this.configure('development', function(){134 this.enable('hints');135 });136137 // default production configuration138 this.configure('production', function(){139 this.enable('view cache');140 });141142 // route manipulation methods143 methods.forEach(function(method){144 self.lookup[method] = function(path){145 return self.routes.lookup(method, path);146 };147148 self.match[method] = function(path){149 return self.routes.match(method, path);150 };151152 self.remove[method] = function(path){153 return self.routes.lookup(method, path).remove();154 };155 });156157 // del -> delete158 self.lookup.del = self.lookup.delete;159 self.match.del = self.match.delete;160 self.remove.del = self.remove.delete;161};162163/**164 * Remove routes matching the given `path`.165 *166 * @param {Route} path167 * @return {Boolean}168 * @api public169 */170171app.remove = function(path){172 return this.routes.lookup('all', path).remove();173};174175/**176 * Lookup routes defined with a path177 * equivalent to `path`.178 *179 * @param {Stirng} path180 * @return {Array}181 * @api public182 */183184app.lookup = function(path){185 return this.routes.lookup('all', path);186};187188/**189 * Lookup routes matching the given `url`.190 *191 * @param {Stirng} url192 * @return {Array}193 * @api public194 */195196app.match = function(url){197 return this.routes.match('all', url);198};199200/**201 * Proxy `connect.HTTPServer#use()` to apply settings to202 * mounted applications.203 *204 * @param {String|Function|Server} route205 * @param {Function|Server} middleware206 * @return {Server} for chaining207 * @api public208 */209210app.use = function(route, middleware){211 var app, home, handle;212213 if ('string' != typeof route) {214 middleware = route, route = '/';215 }216217 // express app218 if (middleware.handle && middleware.set) app = middleware;219220 // restore .app property on req and res221 if (app) {222 app.route = route;223 middleware = function(req, res, next) {224 var orig = req.app;225 app.handle(req, res, function(err){226 req.app = res.app = orig;227 next(err);228 });229 };230 }231232 connect.HTTPServer.prototype.use.call(this, route, middleware);233234 // mounted an app, invoke the hook235 // and adjust some settings236 if (app) {237 home = app.set('home');238 if ('/' == home) home = '';239 app.set('home', app.route + home);240 app.parent = this;241 if (app.__mounted) app.__mounted.call(app, this);242 }243244 return this;245};246247/**248 * Assign a callback `fn` which is called249 * when this `Server` is passed to `Server#use()`.250 *251 * Examples:252 *253 * var app = express.createServer()254 * , blog = express.createServer();255 *256 * blog.mounted(function(parent){257 * // parent is app258 * // "this" is blog259 * });260 *261 * app.use(blog);262 *263 * @param {Function} fn264 * @return {Server} for chaining265 * @api public266 */267268app.mounted = function(fn){269 this.__mounted = fn;270 return this;271};272273/**274 * See: view.register.275 *276 * @return {Server} for chaining277 * @api public278 */279280app.register = function(){281 view.register.apply(this, arguments);282 return this;283};284285/**286<<<<<<< HEAD287 * Map the given param placeholder `name`(s) to the given callback `fn`.288=======289 * Register the given view helpers `obj`. This method290 * can be called several times to apply additional helpers.291 *292 * @param {Object} obj293 * @return {Server} for chaining294 * @api public295 */296297app.helpers =298app.locals = function(obj){299 utils.merge(this._locals, obj);300 return this;301};302303/**304 * Register the given dynamic view helpers `obj`. This method305 * can be called several times to apply additional helpers.306 *307 * @param {Object} obj308 * @return {Server} for chaining309 * @api public310 */311312app.dynamicHelpers = function(obj){313 utils.merge(this.dynamicViewHelpers, obj);314 return this;315};316317/**318 * Map the given param placeholder `name`(s) to the given callback(s).319 *320 * Param mapping is used to provide pre-conditions to routes321 * which us normalized placeholders. This callback has the same322 * signature as regular middleware, for example below when ":userId"323 * is used this function will be invoked in an attempt to load the user.324 *325 * app.param('userId', function(req, res, next, id){326 * User.find(id, function(err, user){327 * if (err) {328 * next(err);329 * } else if (user) {330 * req.user = user;331 * next();332 * } else {333 * next(new Error('failed to load user'));334 * }335 * });336 * });337 *338 * Passing a single function allows you to map logic339 * to the values passed to `app.param()`, for example340 * this is useful to provide coercion support in a concise manner.341 *342 * The following example maps regular expressions to param values343 * ensuring that they match, otherwise passing control to the next344 * route:345 *346 * app.param(function(name, regexp){347 * if (regexp instanceof RegExp) {348 * return function(req, res, next, val){349 * var captures;350 * if (captures = regexp.exec(String(val))) {351 * req.params[name] = captures;352 * next();353 * } else {354 * next('route');355 * }356 * }357 * }358 * });359 *360 * We can now use it as shown below, where "/commit/:commit" expects361 * that the value for ":commit" is at 5 or more digits. The capture362 * groups are then available as `req.params.commit` as we defined363 * in the function above.364 *365 * app.param('commit', /^\d{5,}$/);366 *367 * For more of this useful functionality take a look368 * at [express-params](http://github.com/visionmedia/express-params).369 *370 * @param {String|Array|Function} name371 * @param {Function} fn372 * @return {Server} for chaining373 * @api public374 */375376app.param = function(name, fn){377 var self = this378 , fns = [].slice.call(arguments, 1);379380 // array381 if (Array.isArray(name)) {382 name.forEach(function(name){383 fns.forEach(function(fn){384 self.param(name, fn);385 });386 });387 // param logic388 } else if ('function' == typeof name) {389 this.routes.param(name);390 // single391 } else {392 if (':' == name[0]) name = name.substr(1);393 fns.forEach(function(fn){394 self.routes.param(name, fn);395 });396 }397398 return this;399};400401/**402 * Register the given callback `fn` for the given `type`.403 *404 * @param {String} type405 * @param {Function} fn406 * @return {Server} for chaining407 * @api public408 */409410app.is = function(type, fn){411 if (!fn) return this.isCallbacks[type];412 this.isCallbacks[type] = fn;413 return this;414};415416/**417 * Assign `setting` to `val`, or return `setting`'s value.418 * Mounted servers inherit their parent server's settings.419 *420 * @param {String} setting421 * @param {String} val422 * @return {Server|Mixed} for chaining, or the setting value423 * @api public424 */425426app.set = function(setting, val){427 if (val === undefined) {428 if (this.settings.hasOwnProperty(setting)) {429 return this.settings[setting];430 } else if (this.parent) {431 return this.parent.set(setting);432 }433 } else {434 this.settings[setting] = val;435 return this;436 }437};438439/**440 * Check if `setting` is enabled.441 *442 * @param {String} setting443 * @return {Boolean}444 * @api public445 */446447app.enabled = function(setting){448 return !!this.set(setting);449};450451/**452 * Check if `setting` is disabled.453 *454 * @param {String} setting455 * @return {Boolean}456 * @api public457 */458459app.disabled = function(setting){460 return !this.set(setting);461};462463/**464 * Enable `setting`.465 *466 * @param {String} setting467 * @return {Server} for chaining468 * @api public469 */470471app.enable = function(setting){472 return this.set(setting, true);473};474475/**476 * Disable `setting`.477 *478 * @param {String} setting479 * @return {Server} for chaining480 * @api public481 */482483app.disable = function(setting){484 return this.set(setting, false);485};486487/**488 * Redirect `key` to `url`.489 *490 * @param {String} key491 * @param {String} url492 * @return {Server} for chaining493 * @api public494 */495496app.redirect = function(key, url){497 this.redirects[key] = url;498 return this;499};500501/**502 * Configure callback for zero or more envs,503 * when no env is specified that callback will504 * be invoked for all environments. Any combination505 * can be used multiple times, in any order desired.506 *507 * Examples:508 *509 * app.configure(function(){510 * // executed for all envs511 * });512 *513 * app.configure('stage', function(){514 * // executed staging env515 * });516 *517 * app.configure('stage', 'production', function(){518 * // executed for stage and production519 * });520 *521 * @param {String} env...522 * @param {Function} fn523 * @return {Server} for chaining524 * @api public525 */526527app.configure = function(env, fn){528 var envs = 'all'529 , args = toArray(arguments);530 fn = args.pop();531 if (args.length) envs = args;532 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);533 return this;534};535536/**537 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.538 */539540methods.forEach(function(method){541 app[method] = function(path){542 if (1 == arguments.length) return this.routes.lookup(method, path);543 var args = [method].concat(toArray(arguments));544 if (!this.__usedRouter) this.use(this.router);545 return this.routes._route.apply(this.routes, args);546 }547});548549/**550 * Special-cased "all" method, applying the given route `path`,551 * middleware, and callback to _every_ HTTP method.552 *553 * @param {String} path554 * @param {Function} ...555 * @return {Server} for chaining556 * @api public557 */558559app.all = function(path){560 var args = arguments;561 if (1 == args.length) return this.routes.lookup('all', path);562 methods.forEach(function(method){563 if ('all' == method) return;564 app[method].apply(this, args);565 }, this);566 return this;567};568569// del -> delete alias570571app.del = app.delete;572