Skip to content
Myr

server.js

This file

Path

lib/server.js

458 lines · 9.8 KiB · JavaScript

Last changed by

prepping for connect 1.0Tj Holowaychukbefore adoptionbdbacb4

History of this file

Take it

12/*!3 * Express - Server4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var queryString = require('querystring')13  , connect = require('connect')14  , router = connect.router15  , methods = router.methods.concat(['del', 'all'])16  , view = require('./view')17  , url = require('url')18  , utils = connect.utils;1920/**21 * Initialize a new `Server` with optional `middleware`.22 *23 * @param {Array} middleware24 * @api public25 */2627var Server = exports = module.exports = function Server(middleware){28  var self = this;29  this.settings = {};30  this.redirects = {};31  this.isCallbacks = {};32  this.viewHelpers = {};33  this.dynamicViewHelpers = {};34  this.errorHandlers = [];35  connect.HTTPServer.call(this, []);3637  // Default "home" to / 38  this.set('home', '/');3940  // Set "env" to NODE_ENV, defaulting to "development"41  this.set('env', process.env.NODE_ENV || 'development');4243  // Expose objects to each other44  this.use(function(req, res, next){45    req.query = req.query || {};46    res.headers = { 'X-Powered-By': 'Express' };47    req.app = res.app = self;48    req.res = res;49    res.req = req;50    req.next = next;51    // Assign req.params.get52    if (req.url.indexOf('?') > 0) {53      var query = url.parse(req.url).query;54      req.query = exports.parseQueryString(query);55    }56    next();57  });5859  // Apply middleware60  if (middleware) {61    middleware.forEach(function(fn){62      self.use(fn);63    });64  }6566  // Use router, expose as app.get(), etc67  var fn = router(function(app){ self.routes = app; });68  this.__defineGetter__('router', function(){69    this.__usedRouter = true;70    return fn;71  });7273  // Default production configuration74  this.configure('production', function(){75    this.enable('cache views');76  });77};7879/**80 * Inherit from `connect.HTTPServer`.81 */8283Server.prototype.__proto__ = connect.HTTPServer.prototype;8485/**86 * Support swappable querystring parsers.87 */8889exports.parseQueryString = queryString.parse;9091/**92 * Proxy in order to register error handlers.93 */9495Server.prototype.listen = function(){96  this.registerErrorHandlers();97  connect.HTTPServer.prototype.listen.apply(this, arguments);98};99100/**101 * Proxy in order to register error handlers.102 */103104Server.prototype.listenFD = function(){105  this.registerErrorHandlers();106  connect.HTTPServer.prototype.listenFD.apply(this, arguments);107};108109/**110 * When using the vhost() middleware register error handlers.111 */112113Server.prototype.onvhost = function(){114  this.registerErrorHandlers();115};116117/**118 * Register error handlers. This is automatically119 * called from within `Server#listen()` and `Server#listenFD()`.120 *121 * @return {Server} for chaining122 * @api public123 */124125Server.prototype.registerErrorHandlers = function(){126  this.errorHandlers.forEach(function(fn){127    this.use(function(err, req, res, next){128      fn.apply(this, arguments);129    });130  }, this);131  return this;132};133134/**135 * Proxy `connect.HTTPServer#use()` to apply settings to136 * mounted applications.137 *138 * @param {String|Function|Server} route139 * @param {Function|Server} middleware140 * @return {Server} for chaining141 * @api public142 */143144Server.prototype.use = function(route, middleware){145  if (typeof route !== 'string') {146    middleware = route, route = '/';147  }148149  connect.HTTPServer.prototype.use.call(this, route, middleware);150151  // Mounted an app152  if (middleware instanceof Server) {153    // Home is /:route/:home154    var app = middleware155      , home = app.set('home');156    if (home === '/') home = '';157    app.set('home', (app.route || '') + home);158    app.parent = this;159    // Mounted hook160    if (app.__mounted) app.__mounted.call(app, this);161  }162163  return this;164};165166/**167 * Assign a callback `fn` which is called168 * when this `Server` is passed to `Server#use()`.169 *170 * Examples:171 *172 *    var app = express.createServer(),173 *        blog = express.createServer();174 *175 *    blog.mounted(function(parent){176 *        // parent is app177 *        // "this" is blog178 *    });179 *180 *    app.use(blog);181 *182 * @param {Function} fn183 * @return {Server} for chaining184 * @api public185 */186187Server.prototype.mounted = function(fn){188  this.__mounted = fn;189  return this;190};191192/**193 * See: view.register.194 *195 * @return {Server} for chaining196 * @api public197 */198199Server.prototype.register = function(){200  view.register.apply(this, arguments);201  return this;202};203204/**205 * Register the given view helpers `obj`. This method206 * can be called several times to apply additional helpers.207 *208 * @param {Object} obj209 * @return {Server} for chaining210 * @api public211 */212213Server.prototype.helpers = 214Server.prototype.locals = function(obj){215  utils.merge(this.viewHelpers, obj);216  return this;217};218219/**220 * Register the given dynamic view helpers `obj`. This method221 * can be called several times to apply additional helpers.222 *223 * @param {Object} obj224 * @return {Server} for chaining225 * @api public226 */227228Server.prototype.dynamicHelpers = function(obj){229  utils.merge(this.dynamicViewHelpers, obj);230  return this;231};232233/**234 * Map the given param placeholder `name`(s) to the given callback `fn`.235 *236 * Param mapping is used to provide pre-conditions to routes237 * which us normalized placeholders. For example ":user_id" may238 * attempt to load the user from the database, where as ":num" may 239 * pass the value through `parseInt(num, 10)`.240 *241 * When the callback function accepts only a single argument, the242 * value of placeholder is passed:243 *244 *    app.param('page', function(n){ return parseInt(n, 10); });245 *246 * After which "/users/:page" would automatically provide us with247 * an integer for `req.params.page`. If desired we could use the callback 248 * signature shown below, and immediately `next(new Error('invalid page'))`249 * when `parseInt` fails.250 *251 * Alternatively the callback may accept the request, response, next, and252 * the value, acting like middlware:253 *254 *    app.param('userId', function(req, res, next, id){255 *      User.find(id, function(err, user){256 *        if (err) {257 *          next(err);258 *        } else if (user) {259 *          req.user = user;260 *          next();261 *        } else {262 *          next(new Error('failed to load user'));263 *        }264 *      });265 *    });266 *267 * Now every time ":userId" is present, the associated user object268 * will be loaded and assigned before the route handler is invoked.269 *270 * @param {String|Array} name271 * @param {Function} fn272 * @return {Server} for chaining273 * @api public274 */275276Server.prototype.param = function(name, fn){277  if (Array.isArray(name)) {278    name.forEach(function(name){279      this.param(name, fn);280    }, this);281  } else {282    if (':' == name[0]) name = name.substr(1);283    this.routes.param(name, fn);284  }285  return this;286};287288/**289 * Assign a custom exception handler callback `fn`.290 * These handlers are always _last_ in the middleware stack.291 *292 * @param {Function} fn293 * @return {Server} for chaining294 * @api public295 */296297Server.prototype.error = function(fn){298  this.errorHandlers.push(fn);299  return this;300};301302/**303 * Register the given callback `fn` for the given `type`.304 *305 * @param {String} type306 * @param {Function} fn307 * @return {Server} for chaining308 * @api public309 */310311Server.prototype.is = function(type, fn){312  if (!fn) return this.isCallbacks[type];313  this.isCallbacks[type] = fn;314  return this;315};316317/**318 * Assign `setting` to `val`, or return `setting`'s value.319 * Mounted servers inherit their parent server's settings.320 *321 * @param {String} setting322 * @param {String} val323 * @return {Server|Mixed} for chaining, or the setting value324 * @api public325 */326327Server.prototype.set = function(setting, val){328  if (val === undefined) {329    if (this.settings.hasOwnProperty(setting)) {330      return this.settings[setting];331    } else if (this.parent) {332      return this.parent.set(setting);333    }334  } else {335    this.settings[setting] = val;336    return this;337  }338};339340/**341 * Check if `setting` is enabled.342 *343 * @param {String} setting344 * @return {Boolean}345 * @api public346 */347348Server.prototype.enabled = function(setting){349  return !!this.set(setting);350};351352/**353 * Check if `setting` is disabled.354 *355 * @param {String} setting356 * @return {Boolean}357 * @api public358 */359360Server.prototype.disabled = function(setting){361  return !this.set(setting);362};363364/**365 * Enable `setting`.366 *367 * @param {String} setting368 * @return {Server} for chaining369 * @api public370 */371372Server.prototype.enable = function(setting){373  return this.set(setting, true);374};375376/**377 * Disable `setting`.378 *379 * @param {String} setting380 * @return {Server} for chaining381 * @api public382 */383384Server.prototype.disable = function(setting){385  return this.set(setting, false);386};387388/**389 * Redirect `key` to `url`.390 *391 * @param {String} key392 * @param {String} url393 * @return {Server} for chaining394 * @api public395 */396397Server.prototype.redirect = function(key, url){398  this.redirects[key] = url;399  return this;400};401402/**403 * Configure callback for the given `env`.404 *405 * @param {String} env406 * @param {Function} fn407 * @return {Server} for chaining408 * @api public409 */410411Server.prototype.configure = function(env, fn){412  if (typeof env === 'function') {413    fn = env, env = 'all';414  }415  if ('all' == env || env == this.settings.env) {416    fn.call(this);417  }418  return this;419};420421// Generate routing methods422423function generateMethod(method){424  Server.prototype[method] = function(path, fn){425    var self = this;426427    // Ensure router is mounted428    if (!this.__usedRouter) {429      this.use(this.router);430    }431432    // Route specific middleware support433    if (arguments.length > 2) {434      var args = Array.prototype.slice.call(arguments, 1);435      fn = args.pop();436      (function stack(middleware){437        middleware.forEach(function(fn){438          if (Array.isArray(fn)) {439            stack(fn);440          } else {441            self[method](path, fn);442          }443        });444      })(args);445    }446447    // Generate the route448    this.routes[method](path, fn);449    return this;450  };451  return arguments.callee;452}453454methods.forEach(generateMethod);455456// Alias delete as "del"457458Server.prototype.del = Server.prototype.delete;