Skip to content
Myr

http.js

This file

Path

lib/http.js

504 lines · 10.0 KiB · JavaScript

Last changed by

Changed `app.locals` to match `res.locals`Tj Holowaychukbefore adoption1dc8776

History of this file

Take 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({131      settings: this.settings132    , app: this133  });134135  // default development configuration136  this.configure('development', function(){137    this.enable('hints');138  });139140  // default production configuration141  this.configure('production', function(){142    this.enable('view cache');143  });144145  // route manipulation methods146  methods.forEach(function(method){147    self.lookup[method] = function(path){148      return self.routes.lookup(method, path);149    };150151    self.match[method] = function(path){152      return self.routes.match(method, path);153    };154155    self.remove[method] = function(path){156      return self.routes.lookup(method, path).remove();157    };158  });159160  // del -> delete161  self.lookup.del = self.lookup.delete;162  self.match.del = self.match.delete;163  self.remove.del = self.remove.delete;164};165166/**167 * Remove routes matching the given `path`.168 *169 * @param {Route} path170 * @return {Boolean}171 * @api public172 */173174app.remove = function(path){175  return this.routes.lookup('all', path).remove();176};177178/**179 * Lookup routes defined with a path180 * equivalent to `path`.181 *182 * @param {Stirng} path183 * @return {Array}184 * @api public185 */186187app.lookup = function(path){188  return this.routes.lookup('all', path);189};190191/**192 * Lookup routes matching the given `url`.193 *194 * @param {Stirng} url195 * @return {Array}196 * @api public197 */198199app.match = function(url){200  return this.routes.match('all', url);201};202203/**204 * Proxy `connect.HTTPServer#use()` to apply settings to205 * mounted applications.206 *207 * @param {String|Function|Server} route208 * @param {Function|Server} middleware209 * @return {Server} for chaining210 * @api public211 */212213app.use = function(route, middleware){214  var app, home, handle;215216  if ('string' != typeof route) {217    middleware = route, route = '/';218  }219220  // express app221  if (middleware.handle && middleware.set) app = middleware;222223  // restore .app property on req and res224  if (app) {225    app.route = route;226    middleware = function(req, res, next) {227      var orig = req.app;228      app.handle(req, res, function(err){229        req.app = res.app = orig;230        next(err);231      });232    };233  }234235  connect.HTTPServer.prototype.use.call(this, route, middleware);236237  // mounted an app, invoke the hook238  // and adjust some settings239  if (app) {240    home = app.set('home');241    if ('/' == home) home = '';242    app.set('home', app.route + home);243    app.parent = this;244    if (app.__mounted) app.__mounted.call(app, this);245  }246247  return this;248};249250/**251 * Assign a callback `fn` which is called252 * when this `Server` is passed to `Server#use()`.253 *254 * Examples:255 *256 *    var app = express.createServer()257 *      , blog = express.createServer();258 *259 *    blog.mounted(function(parent){260 *      // parent is app261 *      // "this" is blog262 *    });263 *264 *    app.use(blog);265 *266 * @param {Function} fn267 * @return {Server} for chaining268 * @api public269 */270271app.mounted = function(fn){272  this.__mounted = fn;273  return this;274};275276/**277 * See: view.register.278 *279 * @return {Server} for chaining280 * @api public281 */282283app.register = function(){284  view.register.apply(this, arguments);285  return this;286};287288/**289 * Map the given param placeholder `name`(s) to the given callback `fn`.290 *291 * Param mapping is used to provide pre-conditions to routes292 * which us normalized placeholders. This callback has the same293 * signature as regular middleware, for example below when ":userId"294 * is used this function will be invoked in an attempt to load the user.295 *296 *      app.param('userId', function(req, res, next, id){297 *        User.find(id, function(err, user){298 *          if (err) {299 *            next(err);300 *          } else if (user) {301 *            req.user = user;302 *            next();303 *          } else {304 *            next(new Error('failed to load user'));305 *          }306 *        });307 *      });308 *309 * @param {String|Array|Function} name310 * @param {Function} fn311 * @return {Server} for chaining312 * @api public313 */314315app.param = function(name, fn){316  // array317  if (Array.isArray(name)) {318    name.forEach(function(name){319      this.param(name, fn);320    }, this);321  // param logic322  } else if ('function' == typeof name) {323    this.routes.param(name);324  // single325  } else {326    if (':' == name[0]) name = name.substr(1);327    this.routes.param(name, fn);328  }329330  return this;331};332333/**334 * Register the given callback `fn` for the given `type`.335 *336 * @param {String} type337 * @param {Function} fn338 * @return {Server} for chaining339 * @api public340 */341342app.is = function(type, fn){343  if (!fn) return this.isCallbacks[type];344  this.isCallbacks[type] = fn;345  return this;346};347348/**349 * Assign `setting` to `val`, or return `setting`'s value.350 * Mounted servers inherit their parent server's settings.351 *352 * @param {String} setting353 * @param {String} val354 * @return {Server|Mixed} for chaining, or the setting value355 * @api public356 */357358app.set = function(setting, val){359  if (val === undefined) {360    if (this.settings.hasOwnProperty(setting)) {361      return this.settings[setting];362    } else if (this.parent) {363      return this.parent.set(setting);364    }365  } else {366    this.settings[setting] = val;367    return this;368  }369};370371/**372 * Check if `setting` is enabled.373 *374 * @param {String} setting375 * @return {Boolean}376 * @api public377 */378379app.enabled = function(setting){380  return !!this.set(setting);381};382383/**384 * Check if `setting` is disabled.385 *386 * @param {String} setting387 * @return {Boolean}388 * @api public389 */390391app.disabled = function(setting){392  return !this.set(setting);393};394395/**396 * Enable `setting`.397 *398 * @param {String} setting399 * @return {Server} for chaining400 * @api public401 */402403app.enable = function(setting){404  return this.set(setting, true);405};406407/**408 * Disable `setting`.409 *410 * @param {String} setting411 * @return {Server} for chaining412 * @api public413 */414415app.disable = function(setting){416  return this.set(setting, false);417};418419/**420 * Redirect `key` to `url`.421 *422 * @param {String} key423 * @param {String} url424 * @return {Server} for chaining425 * @api public426 */427428app.redirect = function(key, url){429  this.redirects[key] = url;430  return this;431};432433/**434 * Configure callback for zero or more envs,435 * when no env is specified that callback will436 * be invoked for all environments. Any combination437 * can be used multiple times, in any order desired.438 *439 * Examples:440 *441 *    app.configure(function(){442 *      // executed for all envs443 *    });444 *445 *    app.configure('stage', function(){446 *      // executed staging env447 *    });448 *449 *    app.configure('stage', 'production', function(){450 *      // executed for stage and production451 *    });452 *453 * @param {String} env...454 * @param {Function} fn455 * @return {Server} for chaining456 * @api public457 */458459app.configure = function(env, fn){460  var envs = 'all'461    , args = toArray(arguments);462  fn = args.pop();463  if (args.length) envs = args;464  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);465  return this;466};467468/**469 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.470 */471472methods.forEach(function(method){473  app[method] = function(path){474    if (1 == arguments.length) return this.routes.lookup(method, path);475    var args = [method].concat(toArray(arguments));476    if (!this.__usedRouter) this.use(this.router);477    return this.routes._route.apply(this.routes, args);478  }479});480481/**482 * Special-cased "all" method, applying the given route `path`,483 * middleware, and callback to _every_ HTTP method.484 *485 * @param {String} path486 * @param {Function} ...487 * @return {Server} for chaining488 * @api public489 */490491app.all = function(path){492  var args = arguments;493  if (1 == args.length) return this.routes.lookup('all', path);494  methods.forEach(function(method){495    if ('all' == method) return;496    app[method].apply(this, args);497  }, this);498  return this;499};500501// del -> delete alias502503app.del = app.delete;504