Skip to content
Myr

application.js

This file

Path

lib/application.js

533 lines · 11.8 KiB · JavaScript

Last changed by

Merge pull request #1454 from shtylman/router-http-methodsTJ Holowaychukbefore adoption618484a

History of this file

Take it

The walk stopped after 200 commits: lines older than 6ca1807 point at it.

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 1–6why, one step back
1/**
2 * Module dependencies.3 */45var connect = require('connect')6 , Router = require('./router')

Added "methods" depTJ Holowaychukbefore adoption170dcc2

line 7why, one step back
7 , methods = require('methods')

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 8–14why, one step back
8 , middleware = require('./middleware')
9 , debug = require('debug')('express:application')10 , locals = require('./utils').locals11 , View = require('./view')12 , utils = connect.utils13 , path = require('path')14 , http = require('http')

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2d49c0d

line 15why, one step back
15 , join = path.join;

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 16–48why, one step back
16
17/**18 * Application prototype.19 */2021var app = exports = module.exports = {};2223/**24 * Initialize the server.25 *26 * - setup default configuration27 * - setup default middleware28 * - setup route reflection methods29 *30 * @api private31 */3233app.init = function(){34 this.cache = {};35 this.settings = {};36 this.engines = {};37 this.viewCallbacks = [];38 this.defaultConfiguration();39};4041/**42 * Initialize application configuration.43 *44 * @api private45 */4647app.defaultConfiguration = function(){48 // default settings

add "x-powered-by" settingTJ Holowaychukbefore adoption5ac631a

line 49why, one step back
49 this.enable('x-powered-by');

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 50–56why, one step back
50 this.set('env', process.env.NODE_ENV || 'development');
51 debug('booting in %s mode', this.get('env'));5253 // implicit middleware54 this.use(connect.query());55 this.use(middleware.init(this));56

remove app.locals.use and res.locals.useTJ Holowaychukbefore adoption4f7c4d1

line 57why, one step back
57 // inherit protos

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 58–80why, one step back
58 this.on('mount', function(parent){
59 this.request.__proto__ = parent.request;60 this.response.__proto__ = parent.response;61 this.engines.__proto__ = parent.engines;62 });6364 // router65 this._router = new Router(this);66 this.routes = this._router.map;67 this.__defineGetter__('router', function(){68 this._usedRouter = true;69 this._router.caseSensitive = this.enabled('case sensitive routing');70 this._router.strict = this.enabled('strict routing');71 return this._router.middleware;72 });7374 // setup locals75 this.locals = locals(this);7677 // default locals78 this.locals.settings = this.settings;7980 // default configuration

move default of "views" out so multiple cwd() calls are not madeTJ Holowaychukbefore adoption76d3ec5

line 81why, one step back
81 this.set('views', process.cwd() + '/views');

add "jsonp callback name" settingriadhbefore adoption5426eb0

line 82why, one step back
82 this.set('jsonp callback name', 'callback');

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 83–103why, one step back
83
84 this.configure('development', function(){85 this.set('json spaces', 2);86 });8788 this.configure('production', function(){89 this.enable('view cache');90 });91};9293/**94 * Proxy `connect#use()` to apply settings to95 * mounted applications.96 *97 * @param {String|Function|Server} route98 * @param {Function|Server} fn99 * @return {app} for chaining100 * @api public101 */102103app.use = function(route, fn){

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption1c616e2

line 104why, one step back
104 var app;

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 105–399why, one step back
105
106 // default route to '/'107 if ('string' != typeof route) fn = route, route = '/';108109 // express app110 if (fn.handle && fn.set) app = fn;111112 // restore .app property on req and res113 if (app) {114 app.route = route;115 fn = function(req, res, next) {116 var orig = req.app;117 app.handle(req, res, function(err){118 req.app = res.app = orig;119 req.__proto__ = orig.request;120 res.__proto__ = orig.response;121 next(err);122 });123 };124 }125126 connect.proto.use.call(this, route, fn);127128 // mounted an app129 if (app) {130 app.parent = this;131 app.emit('mount', this);132 }133134 return this;135};136137/**138 * Register the given template engine callback `fn`139 * as `ext`.140 *141 * By default will `require()` the engine based on the142 * file extension. For example if you try to render143 * a "foo.jade" file Express will invoke the following internally:144 *145 * app.engine('jade', require('jade').__express);146 *147 * For engines that do not provide `.__express` out of the box,148 * or if you wish to "map" a different extension to the template engine149 * you may use this method. For example mapping the EJS template engine to150 * ".html" files:151 *152 * app.engine('html', require('ejs').renderFile);153 *154 * In this case EJS provides a `.renderFile()` method with155 * the same signature that Express expects: `(path, options, callback)`,156 * though note that it aliases this method as `ejs.__express` internally157 * so if you're using ".ejs" extensions you dont need to do anything.158 *159 * Some template engines do not follow this convention, the160 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)161 * library was created to map all of node's popular template162 * engines to follow this convention, thus allowing them to163 * work seemlessly within Express.164 *165 * @param {String} ext166 * @param {Function} fn167 * @return {app} for chaining168 * @api public169 */170171app.engine = function(ext, fn){172 if ('function' != typeof fn) throw new Error('callback function required');173 if ('.' != ext[0]) ext = '.' + ext;174 this.engines[ext] = fn;175 return this;176};177178/**179 * Map the given param placeholder `name`(s) to the given callback(s).180 *181 * Parameter mapping is used to provide pre-conditions to routes182 * which use normalized placeholders. For example a _:user_id_ parameter183 * could automatically load a user's information from the database without184 * any additional code,185 *186 * The callback uses the samesignature as middleware, the only differencing187 * being that the value of the placeholder is passed, in this case the _id_188 * of the user. Once the `next()` function is invoked, just like middleware189 * it will continue on to execute the route, or subsequent parameter functions.190 *191 * app.param('user_id', function(req, res, next, id){192 * User.find(id, function(err, user){193 * if (err) {194 * next(err);195 * } else if (user) {196 * req.user = user;197 * next();198 * } else {199 * next(new Error('failed to load user'));200 * }201 * });202 * });203 *204 * @param {String|Array} name205 * @param {Function} fn206 * @return {app} for chaining207 * @api public208 */209210app.param = function(name, fn){211 var self = this212 , fns = [].slice.call(arguments, 1);213214 // array215 if (Array.isArray(name)) {216 name.forEach(function(name){217 fns.forEach(function(fn){218 self.param(name, fn);219 });220 });221 // param logic222 } else if ('function' == typeof name) {223 this._router.param(name);224 // single225 } else {226 if (':' == name[0]) name = name.substr(1);227 fns.forEach(function(fn){228 self._router.param(name, fn);229 });230 }231232 return this;233};234235/**236 * Assign `setting` to `val`, or return `setting`'s value.237 *238 * app.set('foo', 'bar');239 * app.get('foo');240 * // => "bar"241 *242 * Mounted servers inherit their parent server's settings.243 *244 * @param {String} setting245 * @param {String} val246 * @return {Server} for chaining247 * @api public248 */249250app.set = function(setting, val){251 if (1 == arguments.length) {252 if (this.settings.hasOwnProperty(setting)) {253 return this.settings[setting];254 } else if (this.parent) {255 return this.parent.set(setting);256 }257 } else {258 this.settings[setting] = val;259 return this;260 }261};262263/**264 * Return the app's absolute pathname265 * based on the parent(s) that have266 * mounted it.267 *268 * For example if the application was269 * mounted as "/admin", which itself270 * was mounted as "/blog" then the271 * return value would be "/blog/admin".272 *273 * @return {String}274 * @api private275 */276277app.path = function(){278 return this.parent279 ? this.parent.path() + this.route280 : '';281};282283/**284 * Check if `setting` is enabled (truthy).285 *286 * app.enabled('foo')287 * // => false288 *289 * app.enable('foo')290 * app.enabled('foo')291 * // => true292 *293 * @param {String} setting294 * @return {Boolean}295 * @api public296 */297298app.enabled = function(setting){299 return !!this.set(setting);300};301302/**303 * Check if `setting` is disabled.304 *305 * app.disabled('foo')306 * // => true307 *308 * app.enable('foo')309 * app.disabled('foo')310 * // => false311 *312 * @param {String} setting313 * @return {Boolean}314 * @api public315 */316317app.disabled = function(setting){318 return !this.set(setting);319};320321/**322 * Enable `setting`.323 *324 * @param {String} setting325 * @return {app} for chaining326 * @api public327 */328329app.enable = function(setting){330 return this.set(setting, true);331};332333/**334 * Disable `setting`.335 *336 * @param {String} setting337 * @return {app} for chaining338 * @api public339 */340341app.disable = function(setting){342 return this.set(setting, false);343};344345/**346 * Configure callback for zero or more envs,347 * when no `env` is specified that callback will348 * be invoked for all environments. Any combination349 * can be used multiple times, in any order desired.350 *351 * Examples:352 *353 * app.configure(function(){354 * // executed for all envs355 * });356 *357 * app.configure('stage', function(){358 * // executed staging env359 * });360 *361 * app.configure('stage', 'production', function(){362 * // executed for stage and production363 * });364 *365 * Note:366 *367 * These callbacks are invoked immediately, and368 * are effectively sugar for the following:369 *370 * var env = process.env.NODE_ENV || 'development';371 *372 * switch (env) {373 * case 'development':374 * ...375 * break;376 * case 'stage':377 * ...378 * break;379 * case 'production':380 * ...381 * break;382 * }383 *384 * @param {String} env...385 * @param {Function} fn386 * @return {app} for chaining387 * @api public388 */389390app.configure = function(env, fn){391 var envs = 'all'392 , args = [].slice.call(arguments);393 fn = args.pop();394 if (args.length) envs = args;395 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);396 return this;397};398399/**

Merge pull request #1454 from shtylman/router-http-methodsTJ Holowaychukbefore adoption618484a

line 400why, one step back
400 * Delegate `.VERB(...)` calls to `router.VERB(...)`.

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 401–404why, one step back
401 */
402403methods.forEach(function(method){404 app[method] = function(path){

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption1c616e2

line 405why, one step back
405 if ('get' == method && 1 == arguments.length) return this.set(path);

Merge pull request #1454 from shtylman/router-http-methodsTJ Holowaychukbefore adoption618484a

lines 406–407why, one step back
406
407 // if no router attacked yet, attach the router

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

line 408why, one step back
408 if (!this._usedRouter) this.use(this.router);

Merge pull request #1454 from shtylman/router-http-methodsTJ Holowaychukbefore adoption618484a

lines 409–411why, one step back
409
410 // setup route411 this._router[method].apply(this._router, arguments);

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 412–413why, one step back
412 return this;
413 };

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 414–455why, one step back
414});
415416/**417 * Special-cased "all" method, applying the given route `path`,418 * middleware, and callback to _every_ HTTP method.419 *420 * @param {String} path421 * @param {Function} ...422 * @return {app} for chaining423 * @api public424 */425426app.all = function(path){427 var args = arguments;428 methods.forEach(function(method){429 app[method].apply(this, args);430 }, this);431 return this;432};433434// del -> delete alias435436app.del = app.delete;437438/**439 * Render the given view `name` name with `options`440 * and a callback accepting an error and the441 * rendered template string.442 *443 * Example:444 *445 * app.render('email', { name: 'Tobi' }, function(err, html){446 * // ...447 * })448 *449 * @param {String} name450 * @param {String|Function} options or fn451 * @param {Function} fn452 * @api public453 */454455app.render = function(name, options, fn){

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2d49c0d

line 456why, one step back
456 var opts = {}

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 457–468why, one step back
457 , cache = this.cache
458 , engines = this.engines459 , view;460461 // support callback function as second arg462 if ('function' == typeof options) {463 fn = options, options = {};464 }465466 // merge app.locals467 utils.merge(opts, this.locals);468

refactor res.render() to prevent clobbering "locals"TJ Holowaychukbefore adoption6bebe08

lines 469–470why, one step back
469 // merge options._locals
470 if (options._locals) utils.merge(opts, options._locals);

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 471–485why, one step back
471
472 // merge options473 utils.merge(opts, options);474475 // set .cache unless explicitly provided476 opts.cache = null == opts.cache477 ? this.enabled('view cache')478 : opts.cache;479480 // primed cache481 if (opts.cache) view = cache[name];482483 // view484 if (!view) {485 view = new View(name, {

move default of "views" out so multiple cwd() calls are not madeTJ Holowaychukbefore adoption76d3ec5

lines 486–488why, one step back
486 defaultEngine: this.get('view engine'),
487 root: this.get('views'),488 engines: engines

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 489–491why, one step back
489 });
490491 if (!view.path) {

add err.view property for view errors. Closes #1226TJ Holowaychukbefore adoption26eeb64

lines 492–494why, one step back
492 var err = new Error('Failed to lookup view "' + name + '"');
493 err.view = view;494 return fn(err);

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 495–523why, one step back
495 }
496497 // prime the cache498 if (opts.cache) cache[name] = view;499 }500501 // render502 try {503 view.render(opts, fn);504 } catch (err) {505 fn(err);506 }507};508509/**510 * Listen for connections.511 *512 * A node `http.Server` is returned, with this513 * application (which is a `Function`) as its514 * callback. If you wish to create both an HTTP515 * and HTTPS server you may do so with the "http"516 * and "https" modules as shown here:517 *518 * var http = require('http')519 * , https = require('https')520 * , express = require('express')521 * , app = express();522 *523 * http.createServer(app).listen(80);

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption363d0d4

line 524why, one step back
524 * https.createServer({ ... }, app).listen(443);

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6ca1807

lines 525–533why, one step back
525 *
526 * @return {http.Server}527 * @api public528 */529530app.listen = function(){531 var server = http.createServer(this);532 return server.listen.apply(server, arguments);533};