Skip to content
Myr

server.js

This file

Path

lib/server.js

459 lines · 9.8 KiB · JavaScript

Last changed by

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

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 url = require('url')13  , view = require('./view')14  , connect = require('connect')15  , utils = connect.utils16  , queryString = require('querystring')17  , router = require('connect').router18  , methods = router.methods.concat(['del', 'all']);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.config = {};30  this.settings = {};31  this.redirects = {};32  this.isCallbacks = {};33  this.viewHelpers = {};34  this.dynamicViewHelpers = {};35  this.errorHandlers = [];36  connect.Server.call(this, []);3738  // Default "home" to / 39  this.set('home', '/');4041  // Set "env" to NODE_ENV, defaulting to "development"42  this.set('env', process.env.NODE_ENV || 'development');4344  // Expose objects to each other45  this.use(function(req, res, next){46    req.query = {};47    res.headers = { 'X-Powered-By': 'Express' };48    req.app = res.app = self;49    req.res = res;50    res.req = req;51    req.next = next;52    // Assign req.params.get53    if (req.url.indexOf('?') > 0) {54      var query = url.parse(req.url).query;55      req.query = exports.parseQueryString(query);56    }57    next();58  });5960  // Apply middleware61  if (middleware) {62    middleware.forEach(function(fn){63      self.use(fn);64    });65  }6667  // Use router, expose as app.get(), etc68  var fn = router(function(app){ self.routes = app; });69  this.__defineGetter__('router', function(){70    this.__usedRouter = true;71    return fn;72  });7374  // Default production configuration75  this.configure('production', function(){76    this.enable('cache views');77  });78};7980/**81 * Inherit from `connect.Server`.82 */8384Server.prototype.__proto__ = connect.Server.prototype;8586/**87 * Support swappable querystring parsers.88 */8990exports.parseQueryString = queryString.parse;9192/**93 * Proxy in order to register error handlers.94 */9596Server.prototype.listen = function(){97  this.registerErrorHandlers();98  connect.Server.prototype.listen.apply(this, arguments);99};100101/**102 * Proxy in order to register error handlers.103 */104105Server.prototype.listenFD = function(){106  this.registerErrorHandlers();107  connect.Server.prototype.listenFD.apply(this, arguments);108};109110/**111 * When using the vhost() middleware register error handlers.112 */113114Server.prototype.onvhost = function(){115  this.registerErrorHandlers();116};117118/**119 * Register error handlers. This is automatically120 * called from within `Server#listen()` and `Server#listenFD()`.121 *122 * @return {Server} for chaining123 * @api public124 */125126Server.prototype.registerErrorHandlers = function(){127  this.errorHandlers.forEach(function(fn){128    this.use(function(err, req, res, next){129      fn.apply(this, arguments);130    });131  }, this);132  return this;133};134135/**136 * Proxy `connect.Server#use()` to apply settings to137 * mounted applications.138 *139 * @param {String|Function|Server} route140 * @param {Function|Server} middleware141 * @return {Server} for chaining142 * @api public143 */144145Server.prototype.use = function(route, middleware){146  if (typeof route !== 'string') {147    middleware = route, route = '/';148  }149150  connect.Server.prototype.use.call(this, route, middleware);151152  // Mounted an app153  if (middleware instanceof Server) {154    // Home is /:route/:home155    var app = middleware156      , home = app.set('home');157    if (home === '/') home = '';158    app.set('home', (app.route || '') + home);159    app.parent = this;160    // Mounted hook161    if (app.__mounted) app.__mounted.call(app, this);162  }163164  return this;165};166167/**168 * Assign a callback `fn` which is called169 * when this `Server` is passed to `Server#use()`.170 *171 * Examples:172 *173 *    var app = express.createServer(),174 *        blog = express.createServer();175 *176 *    blog.mounted(function(parent){177 *        // parent is app178 *        // "this" is blog179 *    });180 *181 *    app.use(blog);182 *183 * @param {Function} fn184 * @return {Server} for chaining185 * @api public186 */187188Server.prototype.mounted = function(fn){189  this.__mounted = fn;190  return this;191};192193/**194 * See: view.register.195 *196 * @return {Server} for chaining197 * @api public198 */199200Server.prototype.register = function(){201  view.register.apply(this, arguments);202  return this;203};204205/**206 * Register the given view helpers `obj`. This method207 * can be called several times to apply additional helpers.208 *209 * @param {Object} obj210 * @return {Server} for chaining211 * @api public212 */213214Server.prototype.helpers = 215Server.prototype.locals = function(obj){216  utils.merge(this.viewHelpers, obj);217  return this;218};219220/**221 * Register the given dynamic view helpers `obj`. This method222 * can be called several times to apply additional helpers.223 *224 * @param {Object} obj225 * @return {Server} for chaining226 * @api public227 */228229Server.prototype.dynamicHelpers = function(obj){230  utils.merge(this.dynamicViewHelpers, obj);231  return this;232};233234/**235 * Map the given param placeholder `name`(s) to the given callback `fn`.236 *237 * Param mapping is used to provide pre-conditions to routes238 * which us normalized placeholders. For example ":user_id" may239 * attempt to load the user from the database, where as ":num" may 240 * pass the value through `parseInt(num, 10)`.241 *242 * When the callback function accepts only a single argument, the243 * value of placeholder is passed:244 *245 *    app.param('page', function(n){ return parseInt(n, 10); });246 *247 * After which "/users/:page" would automatically provide us with248 * an integer for `req.params.page`. If desired we could use the callback 249 * signature shown below, and immediately `next(new Error('invalid page'))`250 * when `parseInt` fails.251 *252 * Alternatively the callback may accept the request, response, next, and253 * the value, acting like middlware:254 *255 *    app.param('userId', function(req, res, next, id){256 *      User.find(id, function(err, user){257 *        if (err) {258 *          next(err);259 *        } else if (user) {260 *          req.user = user;261 *          next();262 *        } else {263 *          next(new Error('failed to load user'));264 *        }265 *      });266 *    });267 *268 * Now every time ":userId" is present, the associated user object269 * will be loaded and assigned before the route handler is invoked.270 *271 * @param {String|Array} name272 * @param {Function} fn273 * @return {Server} for chaining274 * @api public275 */276277Server.prototype.param = function(name, fn){278  if (Array.isArray(name)) {279    name.forEach(function(name){280      this.param(name, fn);281    }, this);282  } else {283    if (':' == name[0]) name = name.substr(1);284    this.routes.param(name, fn);285  }286  return this;287};288289/**290 * Assign a custom exception handler callback `fn`.291 * These handlers are always _last_ in the middleware stack.292 *293 * @param {Function} fn294 * @return {Server} for chaining295 * @api public296 */297298Server.prototype.error = function(fn){299  this.errorHandlers.push(fn);300  return this;301};302303/**304 * Register the given callback `fn` for the given `type`.305 *306 * @param {String} type307 * @param {Function} fn308 * @return {Server} for chaining309 * @api public310 */311312Server.prototype.is = function(type, fn){313  if (!fn) return this.isCallbacks[type];314  this.isCallbacks[type] = fn;315  return this;316};317318/**319 * Assign `setting` to `val`, or return `setting`'s value.320 * Mounted servers inherit their parent server's settings.321 *322 * @param {String} setting323 * @param {String} val324 * @return {Server|Mixed} for chaining, or the setting value325 * @api public326 */327328Server.prototype.set = function(setting, val){329  if (val === undefined) {330    if (this.settings.hasOwnProperty(setting)) {331      return this.settings[setting];332    } else if (this.parent) {333      return this.parent.set(setting);334    }335  } else {336    this.settings[setting] = val;337    return this;338  }339};340341/**342 * Check if `setting` is enabled.343 *344 * @param {String} setting345 * @return {Boolean}346 * @api public347 */348349Server.prototype.enabled = function(setting){350  return !!this.set(setting);351};352353/**354 * Check if `setting` is disabled.355 *356 * @param {String} setting357 * @return {Boolean}358 * @api public359 */360361Server.prototype.disabled = function(setting){362  return !this.set(setting);363};364365/**366 * Enable `setting`.367 *368 * @param {String} setting369 * @return {Server} for chaining370 * @api public371 */372373Server.prototype.enable = function(setting){374  return this.set(setting, true);375};376377/**378 * Disable `setting`.379 *380 * @param {String} setting381 * @return {Server} for chaining382 * @api public383 */384385Server.prototype.disable = function(setting){386  return this.set(setting, false);387};388389/**390 * Redirect `key` to `url`.391 *392 * @param {String} key393 * @param {String} url394 * @return {Server} for chaining395 * @api public396 */397398Server.prototype.redirect = function(key, url){399  this.redirects[key] = url;400  return this;401};402403/**404 * Configure callback for the given `env`.405 *406 * @param {String} env407 * @param {Function} fn408 * @return {Server} for chaining409 * @api public410 */411412Server.prototype.configure = function(env, fn){413  if (typeof env === 'function') {414    fn = env, env = 'all';415  }416  if ('all' == env || env == this.settings.env) {417    fn.call(this);418  }419  return this;420};421422// Generate routing methods423424function generateMethod(method){425  Server.prototype[method] = function(path, fn){426    var self = this;427428    // Ensure router is mounted429    if (!this.__usedRouter) {430      this.use(this.router);431    }432433    // Route specific middleware support434    if (arguments.length > 2) {435      var args = Array.prototype.slice.call(arguments, 1);436      fn = args.pop();437      (function stack(middleware){438        middleware.forEach(function(fn){439          if (Array.isArray(fn)) {440            stack(fn);441          } else {442            self[method](path, fn);443          }444        });445      })(args);446    }447448    // Generate the route449    this.routes[method](path, fn);450    return this;451  };452  return arguments.callee;453}454455methods.forEach(generateMethod);456457// Alias delete as "del"458459Server.prototype.del = Server.prototype.delete;