application.js
This file
Path
lib/application.js
555 lines · 12.4 KiB · JavaScript
Last changed by
Fix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438
History of this fileTake it
The walk stopped after 200 commits: lines older than 9cf7bba point at it.
deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 1–14why, one step back1/**2 * Module dependencies.3 */45var connect = require('connect')6 , Router = require('./router')7 , methods = require('methods')8 , middleware = require('./middleware')9 , debug = require('debug')('express:application')10 , locals = require('./utils').locals11 , compileETag = require('./utils').compileETag12 , compileTrust = require('./utils').compileTrust13 , View = require('./view')14 , http = require('http');deprecate things with depd moduleDouglas Christopher Wilsonbefore adoption9c731f1
line 15why, one step back15var deprecate = require('depd')('express');Fix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438
line 16why, one step back16var merge = require('utils-merge');deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 17–50why, one step back1718/**19 * Application prototype.20 */2122var app = exports = module.exports = {};2324/**25 * Initialize the server.26 *27 * - setup default configuration28 * - setup default middleware29 * - setup route reflection methods30 *31 * @api private32 */3334app.init = function(){35 this.cache = {};36 this.settings = {};37 this.engines = {};38 this.defaultConfiguration();39};4041/**42 * Initialize application configuration.43 *44 * @api private45 */4647app.defaultConfiguration = function(){48 // default settings49 this.enable('x-powered-by');50 this.set('etag', 'weak');add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
lines 51–52why, one step back51 var env = process.env.NODE_ENV || 'development';52 this.set('env', env);deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 53–55why, one step back53 this.set('subdomain offset', 2);54 this.set('trust proxy', false);55add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
lines 56–57why, one step back56 debug('booting in %s mode', env);57deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 58–90why, one step back58 // implicit middleware59 this.use(connect.query());60 this.use(middleware.init(this));6162 // inherit protos63 this.on('mount', function(parent){64 this.request.__proto__ = parent.request;65 this.response.__proto__ = parent.response;66 this.engines.__proto__ = parent.engines;67 this.settings.__proto__ = parent.settings;68 });6970 // router71 this._router = new Router(this);72 this.routes = this._router.map;73 this.__defineGetter__('router', function(){74 this._usedRouter = true;75 this._router.caseSensitive = this.enabled('case sensitive routing');76 this._router.strict = this.enabled('strict routing');77 return this._router.middleware;78 });7980 // setup locals81 this.locals = locals(this);8283 // default locals84 this.locals.settings = this.settings;8586 // default configuration87 this.set('view', View);88 this.set('views', process.cwd() + '/views');89 this.set('jsonp callback name', 'callback');90add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
line 91why, one step back91 if (env === 'development') {deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
line 92why, one step back92 this.set('json spaces', 2);add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
line 93why, one step back93 }deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
line 94why, one step back94add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
line 95why, one step back95 if (env === 'production') {deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
line 96why, one step back96 this.enable('view cache');add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
line 97why, one step back97 }deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 98–414why, one step back98};99100/**101 * Proxy `connect#use()` to apply settings to102 * mounted applications.103 *104 * @param {String|Function|Server} route105 * @param {Function|Server} fn106 * @return {app} for chaining107 * @api public108 */109110app.use = function(route, fn){111 var app;112113 // default route to '/'114 if ('string' != typeof route) fn = route, route = '/';115116 // express app117 if (fn.handle && fn.set) app = fn;118119 // restore .app property on req and res120 if (app) {121 app.route = route;122 fn = function(req, res, next) {123 var orig = req.app;124 app.handle(req, res, function(err){125 req.__proto__ = orig.request;126 res.__proto__ = orig.response;127 next(err);128 });129 };130 }131132 connect.proto.use.call(this, route, fn);133134 // mounted an app135 if (app) {136 app.parent = this;137 app.emit('mount', this);138 }139140 return this;141};142143/**144 * Register the given template engine callback `fn`145 * as `ext`.146 *147 * By default will `require()` the engine based on the148 * file extension. For example if you try to render149 * a "foo.jade" file Express will invoke the following internally:150 *151 * app.engine('jade', require('jade').__express);152 *153 * For engines that do not provide `.__express` out of the box,154 * or if you wish to "map" a different extension to the template engine155 * you may use this method. For example mapping the EJS template engine to156 * ".html" files:157 *158 * app.engine('html', require('ejs').renderFile);159 *160 * In this case EJS provides a `.renderFile()` method with161 * the same signature that Express expects: `(path, options, callback)`,162 * though note that it aliases this method as `ejs.__express` internally163 * so if you're using ".ejs" extensions you dont need to do anything.164 *165 * Some template engines do not follow this convention, the166 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)167 * library was created to map all of node's popular template168 * engines to follow this convention, thus allowing them to169 * work seamlessly within Express.170 *171 * @param {String} ext172 * @param {Function} fn173 * @return {app} for chaining174 * @api public175 */176177app.engine = function(ext, fn){178 if ('function' != typeof fn) throw new Error('callback function required');179 if ('.' != ext[0]) ext = '.' + ext;180 this.engines[ext] = fn;181 return this;182};183184/**185 * Map the given param placeholder `name`(s) to the given callback(s).186 *187 * Parameter mapping is used to provide pre-conditions to routes188 * which use normalized placeholders. For example a _:user_id_ parameter189 * could automatically load a user's information from the database without190 * any additional code,191 *192 * The callback uses the same signature as middleware, the only difference193 * being that the value of the placeholder is passed, in this case the _id_194 * of the user. Once the `next()` function is invoked, just like middleware195 * it will continue on to execute the route, or subsequent parameter functions.196 *197 * app.param('user_id', function(req, res, next, id){198 * User.find(id, function(err, user){199 * if (err) {200 * next(err);201 * } else if (user) {202 * req.user = user;203 * next();204 * } else {205 * next(new Error('failed to load user'));206 * }207 * });208 * });209 *210 * @param {String|Array} name211 * @param {Function} fn212 * @return {app} for chaining213 * @api public214 */215216app.param = function(name, fn){217 var self = this218 , fns = [].slice.call(arguments, 1);219220 // array221 if (Array.isArray(name)) {222 name.forEach(function(name){223 fns.forEach(function(fn){224 self.param(name, fn);225 });226 });227 // param logic228 } else if ('function' == typeof name) {229 this._router.param(name);230 // single231 } else {232 if (':' == name[0]) name = name.substr(1);233 fns.forEach(function(fn){234 self._router.param(name, fn);235 });236 }237238 return this;239};240241/**242 * Assign `setting` to `val`, or return `setting`'s value.243 *244 * app.set('foo', 'bar');245 * app.get('foo');246 * // => "bar"247 *248 * Mounted servers inherit their parent server's settings.249 *250 * @param {String} setting251 * @param {*} [val]252 * @return {Server} for chaining253 * @api public254 */255256app.set = function(setting, val){257 if (arguments.length === 1) {258 // app.get(setting)259 return this.settings[setting];260 }261262 // set value263 this.settings[setting] = val;264265 // trigger matched settings266 switch (setting) {267 case 'etag':268 debug('compile etag %s', val);269 this.set('etag fn', compileETag(val));270 break;271 case 'trust proxy':272 debug('compile trust proxy %s', val);273 this.set('trust proxy fn', compileTrust(val));274 break;275 }276277 return this;278};279280/**281 * Return the app's absolute pathname282 * based on the parent(s) that have283 * mounted it.284 *285 * For example if the application was286 * mounted as "/admin", which itself287 * was mounted as "/blog" then the288 * return value would be "/blog/admin".289 *290 * @return {String}291 * @api private292 */293294app.path = function(){295 return this.parent296 ? this.parent.path() + this.route297 : '';298};299300/**301 * Check if `setting` is enabled (truthy).302 *303 * app.enabled('foo')304 * // => false305 *306 * app.enable('foo')307 * app.enabled('foo')308 * // => true309 *310 * @param {String} setting311 * @return {Boolean}312 * @api public313 */314315app.enabled = function(setting){316 return !!this.set(setting);317};318319/**320 * Check if `setting` is disabled.321 *322 * app.disabled('foo')323 * // => true324 *325 * app.enable('foo')326 * app.disabled('foo')327 * // => false328 *329 * @param {String} setting330 * @return {Boolean}331 * @api public332 */333334app.disabled = function(setting){335 return !this.set(setting);336};337338/**339 * Enable `setting`.340 *341 * @param {String} setting342 * @return {app} for chaining343 * @api public344 */345346app.enable = function(setting){347 return this.set(setting, true);348};349350/**351 * Disable `setting`.352 *353 * @param {String} setting354 * @return {app} for chaining355 * @api public356 */357358app.disable = function(setting){359 return this.set(setting, false);360};361362/**363 * Configure callback for zero or more envs,364 * when no `env` is specified that callback will365 * be invoked for all environments. Any combination366 * can be used multiple times, in any order desired.367 *368 * Examples:369 *370 * app.configure(function(){371 * // executed for all envs372 * });373 *374 * app.configure('stage', function(){375 * // executed staging env376 * });377 *378 * app.configure('stage', 'production', function(){379 * // executed for stage and production380 * });381 *382 * Note:383 *384 * These callbacks are invoked immediately, and385 * are effectively sugar for the following:386 *387 * var env = process.env.NODE_ENV || 'development';388 *389 * switch (env) {390 * case 'development':391 * ...392 * break;393 * case 'stage':394 * ...395 * break;396 * case 'production':397 * ...398 * break;399 * }400 *401 * @param {String} env...402 * @param {Function} fn403 * @return {app} for chaining404 * @api public405 */406407app.configure = function(env, fn){408 var envs = 'all'409 , args = [].slice.call(arguments);410 fn = args.pop();411 if (args.length) envs = args;412 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);413 return this;414};add deprecation message to app.configureDouglas Christopher Wilsonbefore adoption185e327
lines 415–417why, one step back415416app.configure = deprecate.function(app.configure,417 'app.configure: Check app.get(\'env\') in an if statement');deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 418–455why, one step back418419/**420 * Delegate `.VERB(...)` calls to `router.VERB(...)`.421 */422423methods.forEach(function(method){424 app[method] = function(path){425 if ('get' == method && 1 == arguments.length) return this.set(path);426427 // if no router attached yet, attach the router428 if (!this._usedRouter) this.use(this.router);429430 // setup route431 this._router[method].apply(this._router, arguments);432 return this;433 };434});435436/**437 * Special-cased "all" method, applying the given route `path`,438 * middleware, and callback to _every_ HTTP method.439 *440 * @param {String} path441 * @param {Function} ...442 * @return {app} for chaining443 * @api public444 */445446app.all = function(path){447 var args = arguments;448 methods.forEach(function(method){449 app[method].apply(this, args);450 }, this);451 return this;452};453454// del -> delete alias455deprecate things with depd moduleDouglas Christopher Wilsonbefore adoption9c731f1
line 456why, one step back456app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 457–486why, one step back457458/**459 * Render the given view `name` name with `options`460 * and a callback accepting an error and the461 * rendered template string.462 *463 * Example:464 *465 * app.render('email', { name: 'Tobi' }, function(err, html){466 * // ...467 * })468 *469 * @param {String} name470 * @param {String|Function} options or fn471 * @param {Function} fn472 * @api public473 */474475app.render = function(name, options, fn){476 var opts = {}477 , cache = this.cache478 , engines = this.engines479 , view;480481 // support callback function as second arg482 if ('function' == typeof options) {483 fn = options, options = {};484 }485486 // merge app.localsFix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438
line 487why, one step back487 merge(opts, this.locals);deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 488–489why, one step back488489 // merge options._localsFix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438
lines 490–492why, one step back490 if (options._locals) {491 merge(opts, options._locals);492 }deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 493–494why, one step back493494 // merge optionsFix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438
line 495why, one step back495 merge(opts, options);deps: connect@2.19.4Douglas Christopher Wilsonbefore adoption9cf7bba
lines 496–555why, one step back496497 // set .cache unless explicitly provided498 opts.cache = null == opts.cache499 ? this.enabled('view cache')500 : opts.cache;501502 // primed cache503 if (opts.cache) view = cache[name];504505 // view506 if (!view) {507 view = new (this.get('view'))(name, {508 defaultEngine: this.get('view engine'),509 root: this.get('views'),510 engines: engines511 });512513 if (!view.path) {514 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');515 err.view = view;516 return fn(err);517 }518519 // prime the cache520 if (opts.cache) cache[name] = view;521 }522523 // render524 try {525 view.render(opts, fn);526 } catch (err) {527 fn(err);528 }529};530531/**532 * Listen for connections.533 *534 * A node `http.Server` is returned, with this535 * application (which is a `Function`) as its536 * callback. If you wish to create both an HTTP537 * and HTTPS server you may do so with the "http"538 * and "https" modules as shown here:539 *540 * var http = require('http')541 * , https = require('https')542 * , express = require('express')543 * , app = express();544 *545 * http.createServer(app).listen(80);546 * https.createServer({ ... }, app).listen(443);547 *548 * @return {http.Server}549 * @api public550 */551552app.listen = function(){553 var server = http.createServer(this);554 return server.listen.apply(server, arguments);555};