Skip to content
Myr

application.js

This file

Path

lib/application.js

534 lines · 11.8 KiB · JavaScript

Last changed by

typoTJ Holowaychukbefore adoption8942722

History of this file

Take it

The walk stopped after 200 commits: lines older than 3c6ad53 point at it.

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

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')

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

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;

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

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');

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

line 50why, one step back
50 this.set('env', process.env.NODE_ENV || 'development');

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 51why, one step back
51 this.set('subdomain offset', 2);

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 52–57why, one step back
52 debug('booting in %s mode', this.get('env'));
5354 // implicit middleware55 this.use(connect.query());56 this.use(middleware.init(this));57

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 59–81why, one step back
59 this.on('mount', function(parent){
60 this.request.__proto__ = parent.request;61 this.response.__proto__ = parent.response;62 this.engines.__proto__ = parent.engines;63 });6465 // router66 this._router = new Router(this);67 this.routes = this._router.map;68 this.__defineGetter__('router', function(){69 this._usedRouter = true;70 this._router.caseSensitive = this.enabled('case sensitive routing');71 this._router.strict = this.enabled('strict routing');72 return this._router.middleware;73 });7475 // setup locals76 this.locals = locals(this);7778 // default locals79 this.locals.settings = this.settings;8081 // default configuration

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

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

add "jsonp callback name" settingriadhbefore adoption5426eb0

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 84–104why, one step back
84
85 this.configure('development', function(){86 this.set('json spaces', 2);87 });8889 this.configure('production', function(){90 this.enable('view cache');91 });92};9394/**95 * Proxy `connect#use()` to apply settings to96 * mounted applications.97 *98 * @param {String|Function|Server} route99 * @param {Function|Server} fn100 * @return {app} for chaining101 * @api public102 */103104app.use = function(route, fn){

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

line 105why, one step back
105 var app;

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 106–163why, one step back
106
107 // default route to '/'108 if ('string' != typeof route) fn = route, route = '/';109110 // express app111 if (fn.handle && fn.set) app = fn;112113 // restore .app property on req and res114 if (app) {115 app.route = route;116 fn = function(req, res, next) {117 var orig = req.app;118 app.handle(req, res, function(err){119 req.app = res.app = orig;120 req.__proto__ = orig.request;121 res.__proto__ = orig.response;122 next(err);123 });124 };125 }126127 connect.proto.use.call(this, route, fn);128129 // mounted an app130 if (app) {131 app.parent = this;132 app.emit('mount', this);133 }134135 return this;136};137138/**139 * Register the given template engine callback `fn`140 * as `ext`.141 *142 * By default will `require()` the engine based on the143 * file extension. For example if you try to render144 * a "foo.jade" file Express will invoke the following internally:145 *146 * app.engine('jade', require('jade').__express);147 *148 * For engines that do not provide `.__express` out of the box,149 * or if you wish to "map" a different extension to the template engine150 * you may use this method. For example mapping the EJS template engine to151 * ".html" files:152 *153 * app.engine('html', require('ejs').renderFile);154 *155 * In this case EJS provides a `.renderFile()` method with156 * the same signature that Express expects: `(path, options, callback)`,157 * though note that it aliases this method as `ejs.__express` internally158 * so if you're using ".ejs" extensions you dont need to do anything.159 *160 * Some template engines do not follow this convention, the161 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)162 * library was created to map all of node's popular template163 * engines to follow this convention, thus allowing them to

typoTJ Holowaychukbefore adoption8942722

line 164why, one step back
164 * work seamlessly within Express.

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 165–400why, one step back
165 *
166 * @param {String} ext167 * @param {Function} fn168 * @return {app} for chaining169 * @api public170 */171172app.engine = function(ext, fn){173 if ('function' != typeof fn) throw new Error('callback function required');174 if ('.' != ext[0]) ext = '.' + ext;175 this.engines[ext] = fn;176 return this;177};178179/**180 * Map the given param placeholder `name`(s) to the given callback(s).181 *182 * Parameter mapping is used to provide pre-conditions to routes183 * which use normalized placeholders. For example a _:user_id_ parameter184 * could automatically load a user's information from the database without185 * any additional code,186 *187 * The callback uses the samesignature as middleware, the only differencing188 * being that the value of the placeholder is passed, in this case the _id_189 * of the user. Once the `next()` function is invoked, just like middleware190 * it will continue on to execute the route, or subsequent parameter functions.191 *192 * app.param('user_id', function(req, res, next, id){193 * User.find(id, function(err, user){194 * if (err) {195 * next(err);196 * } else if (user) {197 * req.user = user;198 * next();199 * } else {200 * next(new Error('failed to load user'));201 * }202 * });203 * });204 *205 * @param {String|Array} name206 * @param {Function} fn207 * @return {app} for chaining208 * @api public209 */210211app.param = function(name, fn){212 var self = this213 , fns = [].slice.call(arguments, 1);214215 // array216 if (Array.isArray(name)) {217 name.forEach(function(name){218 fns.forEach(function(fn){219 self.param(name, fn);220 });221 });222 // param logic223 } else if ('function' == typeof name) {224 this._router.param(name);225 // single226 } else {227 if (':' == name[0]) name = name.substr(1);228 fns.forEach(function(fn){229 self._router.param(name, fn);230 });231 }232233 return this;234};235236/**237 * Assign `setting` to `val`, or return `setting`'s value.238 *239 * app.set('foo', 'bar');240 * app.get('foo');241 * // => "bar"242 *243 * Mounted servers inherit their parent server's settings.244 *245 * @param {String} setting246 * @param {String} val247 * @return {Server} for chaining248 * @api public249 */250251app.set = function(setting, val){252 if (1 == arguments.length) {253 if (this.settings.hasOwnProperty(setting)) {254 return this.settings[setting];255 } else if (this.parent) {256 return this.parent.set(setting);257 }258 } else {259 this.settings[setting] = val;260 return this;261 }262};263264/**265 * Return the app's absolute pathname266 * based on the parent(s) that have267 * mounted it.268 *269 * For example if the application was270 * mounted as "/admin", which itself271 * was mounted as "/blog" then the272 * return value would be "/blog/admin".273 *274 * @return {String}275 * @api private276 */277278app.path = function(){279 return this.parent280 ? this.parent.path() + this.route281 : '';282};283284/**285 * Check if `setting` is enabled (truthy).286 *287 * app.enabled('foo')288 * // => false289 *290 * app.enable('foo')291 * app.enabled('foo')292 * // => true293 *294 * @param {String} setting295 * @return {Boolean}296 * @api public297 */298299app.enabled = function(setting){300 return !!this.set(setting);301};302303/**304 * Check if `setting` is disabled.305 *306 * app.disabled('foo')307 * // => true308 *309 * app.enable('foo')310 * app.disabled('foo')311 * // => false312 *313 * @param {String} setting314 * @return {Boolean}315 * @api public316 */317318app.disabled = function(setting){319 return !this.set(setting);320};321322/**323 * Enable `setting`.324 *325 * @param {String} setting326 * @return {app} for chaining327 * @api public328 */329330app.enable = function(setting){331 return this.set(setting, true);332};333334/**335 * Disable `setting`.336 *337 * @param {String} setting338 * @return {app} for chaining339 * @api public340 */341342app.disable = function(setting){343 return this.set(setting, false);344};345346/**347 * Configure callback for zero or more envs,348 * when no `env` is specified that callback will349 * be invoked for all environments. Any combination350 * can be used multiple times, in any order desired.351 *352 * Examples:353 *354 * app.configure(function(){355 * // executed for all envs356 * });357 *358 * app.configure('stage', function(){359 * // executed staging env360 * });361 *362 * app.configure('stage', 'production', function(){363 * // executed for stage and production364 * });365 *366 * Note:367 *368 * These callbacks are invoked immediately, and369 * are effectively sugar for the following:370 *371 * var env = process.env.NODE_ENV || 'development';372 *373 * switch (env) {374 * case 'development':375 * ...376 * break;377 * case 'stage':378 * ...379 * break;380 * case 'production':381 * ...382 * break;383 * }384 *385 * @param {String} env...386 * @param {Function} fn387 * @return {app} for chaining388 * @api public389 */390391app.configure = function(env, fn){392 var envs = 'all'393 , args = [].slice.call(arguments);394 fn = args.pop();395 if (args.length) envs = args;396 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);397 return this;398};399400/**

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 402–405why, one step back
402 */
403404methods.forEach(function(method){405 app[method] = function(path){

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

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

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

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

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

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

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 415–456why, one step back
415});
416417/**418 * Special-cased "all" method, applying the given route `path`,419 * middleware, and callback to _every_ HTTP method.420 *421 * @param {String} path422 * @param {Function} ...423 * @return {app} for chaining424 * @api public425 */426427app.all = function(path){428 var args = arguments;429 methods.forEach(function(method){430 app[method].apply(this, args);431 }, this);432 return this;433};434435// del -> delete alias436437app.del = app.delete;438439/**440 * Render the given view `name` name with `options`441 * and a callback accepting an error and the442 * rendered template string.443 *444 * Example:445 *446 * app.render('email', { name: 'Tobi' }, function(err, html){447 * // ...448 * })449 *450 * @param {String} name451 * @param {String|Function} options or fn452 * @param {Function} fn453 * @api public454 */455456app.render = function(name, options, fn){

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 458–469why, one step back
458 , cache = this.cache
459 , engines = this.engines460 , view;461462 // support callback function as second arg463 if ('function' == typeof options) {464 fn = options, options = {};465 }466467 // merge app.locals468 utils.merge(opts, this.locals);469

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 472–486why, one step back
472
473 // merge options474 utils.merge(opts, options);475476 // set .cache unless explicitly provided477 opts.cache = null == opts.cache478 ? this.enabled('view cache')479 : opts.cache;480481 // primed cache482 if (opts.cache) view = cache[name];483484 // view485 if (!view) {486 view = new View(name, {

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 490–492why, one step back
490 });
491492 if (!view.path) {

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

lines 496–524why, one step back
496 }
497498 // prime the cache499 if (opts.cache) cache[name] = view;500 }501502 // render503 try {504 view.render(opts, fn);505 } catch (err) {506 fn(err);507 }508};509510/**511 * Listen for connections.512 *513 * A node `http.Server` is returned, with this514 * application (which is a `Function`) as its515 * callback. If you wish to create both an HTTP516 * and HTTPS server you may do so with the "http"517 * and "https" modules as shown here:518 *519 * var http = require('http')520 * , https = require('https')521 * , express = require('express')522 * , app = express();523 *524 * http.createServer(app).listen(80);

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

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

Release 3.0.0beta1TJ Holowaychukbefore adoption3c6ad53

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