Skip to content
Myr

http.js

This file

Path

lib/http.js

556 lines · 11.6 KiB · JavaScript

Last changed by

removed dynamicHelpersTj Holowaychukbefore adoption5785e7e

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 connect = require('connect')13  , router = require('./router')14  , Router = require('./router')15  , view = require('./view')16  , toArray = require('./utils').toArray17  , methods = router.methods.concat('del', 'all')18  , res = require('./response')19  , url = require('url')20  , utils = connect.utils21  , qs = require('qs');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    base = this.set('basepath') || this.route;238    if ('/' == base) base = '';239    base = base + (app.set('basepath') || app.route);240    app.set('basepath', base);241    app.parent = this;242    if (app.__mounted) app.__mounted.call(app, this);243  }244245  return this;246};247248/**249 * Assign a callback `fn` which is called250 * when this `Server` is passed to `Server#use()`.251 *252 * Examples:253 *254 *    var app = express.createServer()255 *      , blog = express.createServer();256 *257 *    blog.mounted(function(parent){258 *      // parent is app259 *      // "this" is blog260 *    });261 *262 *    app.use(blog);263 *264 * @param {Function} fn265 * @return {Server} for chaining266 * @api public267 */268269app.mounted = function(fn){270  this.__mounted = fn;271  return this;272};273274/**275 * See: view.register.276 *277 * @return {Server} for chaining278 * @api public279 */280281app.register = function(){282  view.register.apply(this, arguments);283  return this;284};285286/**287 * Map the given param placeholder `name`(s) to the given callback `fn`.288 * Register the given view helpers `obj`. This method289 * can be called several times to apply additional helpers.290 *291 * @param {Object} obj292 * @return {Server} for chaining293 * @api public294 */295296app.locals = function(obj){297  utils.merge(this._locals, obj);298  return this;299};300301/**302 * Map the given param placeholder `name`(s) to the given callback(s).303 *304 * Param mapping is used to provide pre-conditions to routes305 * which us normalized placeholders. This callback has the same306 * signature as regular middleware, for example below when ":userId"307 * is used this function will be invoked in an attempt to load the user.308 *309 *      app.param('userId', function(req, res, next, id){310 *        User.find(id, function(err, user){311 *          if (err) {312 *            next(err);313 *          } else if (user) {314 *            req.user = user;315 *            next();316 *          } else {317 *            next(new Error('failed to load user'));318 *          }319 *        });320 *      });321 *322 * Passing a single function allows you to map logic323 * to the values passed to `app.param()`, for example324 * this is useful to provide coercion support in a concise manner.325 *326 * The following example maps regular expressions to param values327 * ensuring that they match, otherwise passing control to the next328 * route:329 *330 *      app.param(function(name, regexp){331 *        if (regexp instanceof RegExp) {332 *          return function(req, res, next, val){333 *            var captures;334 *            if (captures = regexp.exec(String(val))) {335 *              req.params[name] = captures;336 *              next();337 *            } else {338 *              next('route');339 *            }340 *          }341 *        }342 *      });343 *344 * We can now use it as shown below, where "/commit/:commit" expects345 * that the value for ":commit" is at 5 or more digits. The capture346 * groups are then available as `req.params.commit` as we defined347 * in the function above.348 *349 *    app.param('commit', /^\d{5,}$/);350 *351 * For more of this useful functionality take a look352 * at [express-params](http://github.com/visionmedia/express-params).353 *354 * @param {String|Array|Function} name355 * @param {Function} fn356 * @return {Server} for chaining357 * @api public358 */359360app.param = function(name, fn){361  var self = this362    , fns = [].slice.call(arguments, 1);363364  // array365  if (Array.isArray(name)) {366    name.forEach(function(name){367      fns.forEach(function(fn){368        self.param(name, fn);369      });370    });371  // param logic372  } else if ('function' == typeof name) {373    this.routes.param(name);374  // single375  } else {376    if (':' == name[0]) name = name.substr(1);377    fns.forEach(function(fn){378      self.routes.param(name, fn);379    });380  }381382  return this;383};384385/**386 * Register the given callback `fn` for the given `type`.387 *388 * @param {String} type389 * @param {Function} fn390 * @return {Server} for chaining391 * @api public392 */393394app.is = function(type, fn){395  if (!fn) return this.isCallbacks[type];396  this.isCallbacks[type] = fn;397  return this;398};399400/**401 * Assign `setting` to `val`, or return `setting`'s value.402 * Mounted servers inherit their parent server's settings.403 *404 * @param {String} setting405 * @param {String} val406 * @return {Server|Mixed} for chaining, or the setting value407 * @api public408 */409410app.set = function(setting, val){411  if (val === undefined) {412    if (this.settings.hasOwnProperty(setting)) {413      return this.settings[setting];414    } else if (this.parent) {415      return this.parent.set(setting);416    }417  } else {418    this.settings[setting] = val;419    return this;420  }421};422423/**424 * Check if `setting` is enabled.425 *426 * @param {String} setting427 * @return {Boolean}428 * @api public429 */430431app.enabled = function(setting){432  return !!this.set(setting);433};434435/**436 * Check if `setting` is disabled.437 *438 * @param {String} setting439 * @return {Boolean}440 * @api public441 */442443app.disabled = function(setting){444  return !this.set(setting);445};446447/**448 * Enable `setting`.449 *450 * @param {String} setting451 * @return {Server} for chaining452 * @api public453 */454455app.enable = function(setting){456  return this.set(setting, true);457};458459/**460 * Disable `setting`.461 *462 * @param {String} setting463 * @return {Server} for chaining464 * @api public465 */466467app.disable = function(setting){468  return this.set(setting, false);469};470471/**472 * Redirect `key` to `url`.473 *474 * @param {String} key475 * @param {String} url476 * @return {Server} for chaining477 * @api public478 */479480app.redirect = function(key, url){481  this.redirects[key] = url;482  return this;483};484485/**486 * Configure callback for zero or more envs,487 * when no env is specified that callback will488 * be invoked for all environments. Any combination489 * can be used multiple times, in any order desired.490 *491 * Examples:492 *493 *    app.configure(function(){494 *      // executed for all envs495 *    });496 *497 *    app.configure('stage', function(){498 *      // executed staging env499 *    });500 *501 *    app.configure('stage', 'production', function(){502 *      // executed for stage and production503 *    });504 *505 * @param {String} env...506 * @param {Function} fn507 * @return {Server} for chaining508 * @api public509 */510511app.configure = function(env, fn){512  var envs = 'all'513    , args = toArray(arguments);514  fn = args.pop();515  if (args.length) envs = args;516  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);517  return this;518};519520/**521 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.522 */523524methods.forEach(function(method){525  app[method] = function(path){526    if (1 == arguments.length) return this.routes.lookup(method, path);527    var args = [method].concat(toArray(arguments));528    if (!this.__usedRouter) this.use(this.router);529    return this.routes._route.apply(this.routes, args);530  }531});532533/**534 * Special-cased "all" method, applying the given route `path`,535 * middleware, and callback to _every_ HTTP method.536 *537 * @param {String} path538 * @param {Function} ...539 * @return {Server} for chaining540 * @api public541 */542543app.all = function(path){544  var args = arguments;545  if (1 == args.length) return this.routes.lookup('all', path);546  methods.forEach(function(method){547    if ('all' == method) return;548    app[method].apply(this, args);549  }, this);550  return this;551};552553// del -> delete alias554555app.del = app.delete;556