Skip to content
Myr

application.js

This file

Path

lib/application.js

540 lines · 11.6 KiB · JavaScript

Last changed by

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

History of this file

Take it

The walk stopped after 200 commits: lines older than 9bc63d9 point at it.

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 1–4why, one step back
1/**
2 * Module dependencies.3 */4

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 5why, one step back
5var finalhandler = require('finalhandler');

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 6–13why, one step back
6var mixin = require('utils-merge');
7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var query = require('./middleware/query');11var debug = require('debug')('express:application');12var View = require('./view');13var http = require('http');

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 14why, one step back
14var compileETag = require('./utils').compileETag;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 15why, one step back
15var compileTrust = require('./utils').compileTrust;

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 16why, one step back
16var deprecate = require('depd')('express');

Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48

line 17why, one step back
17var resolve = require('path').resolve;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 18–50why, one step back
18
19/**20 * Application prototype.21 */2223var app = exports = module.exports = {};2425/**26 * Initialize the server.27 *28 * - setup default configuration29 * - setup default middleware30 * - setup route reflection methods31 *32 * @api private33 */3435app.init = function(){36 this.cache = {};37 this.settings = {};38 this.engines = {};39 this.defaultConfiguration();40};4142/**43 * Initialize application configuration.44 *45 * @api private46 */4748app.defaultConfiguration = function(){49 // default settings50 this.enable('x-powered-by');

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 51why, one step back
51 this.set('etag', 'weak');

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 52–54why, one step back
52 var env = process.env.NODE_ENV || 'development';
53 this.set('env', env);54 this.set('subdomain offset', 2);

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 55why, one step back
55 this.set('trust proxy', false);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 56–77why, one step back
56
57 debug('booting in %s mode', env);5859 // inherit protos60 this.on('mount', function(parent){61 this.request.__proto__ = parent.request;62 this.response.__proto__ = parent.response;63 this.engines.__proto__ = parent.engines;64 this.settings.__proto__ = parent.settings;65 });6667 // setup locals68 this.locals = Object.create(null);6970 // top-most app is mounted at /71 this.mountpath = '/';7273 // default locals74 this.locals.settings = this.settings;7576 // default configuration77 this.set('view', View);

Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48

line 78why, one step back
78 this.set('views', resolve('views'));

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 79–106why, one step back
79 this.set('jsonp callback name', 'callback');
8081 if (env === 'production') {82 this.enable('view cache');83 }8485 Object.defineProperty(this, 'router', {86 get: function() {87 throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');88 }89 });90};9192/**93 * lazily adds the base router if it has not yet been added.94 *95 * We cannot add the base router in the defaultConfiguration because96 * it reads app settings which might be set after that has run.97 *98 * @api private99 */100app.lazyrouter = function() {101 if (!this._router) {102 this._router = new Router({103 caseSensitive: this.enabled('case sensitive routing'),104 strict: this.enabled('strict routing')105 });106

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

line 107why, one step back
107 this._router.use(query());

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 108–121why, one step back
108 this._router.use(middleware.init(this));
109 }110};111112/**113 * Dispatch a req, res pair into the application. Starts pipeline processing.114 *115 * If no _done_ callback is provided, then default error handlers will respond116 * in the event of an error bubbling through the stack.117 *118 * @api private119 */120121app.handle = function(req, res, done) {

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 122–123why, one step back
122 var router = this._router;
123

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 124–127why, one step back
124 // final handler
125 done = done || finalhandler(req, res, {126 env: this.get('env'),127 onerror: logerror.bind(this)

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 128why, one step back
128 });

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 129why, one step back
129

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 130–137why, one step back
130 // no routes
131 if (!router) {132 debug('no routes defined on app');133 done();134 return;135 }136137 router.handle(req, res, done);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 138–149why, one step back
138};
139140/**141 * Proxy `Router#use()` to add middleware to the app router.142 * See Router#use() documentation for details.143 *144 * If the _fn_ parameter is an express app, then it will be145 * mounted at the _route_ specified.146 *147 * @api public148 */149

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

line 150why, one step back
150app.use = function use(path, fn){

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 151–152why, one step back
151 var mount_app;
152

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

lines 153–157why, one step back
153 // default path to '/'
154 if (arguments.length < 2) {155 fn = path;156 path = '/';157 }

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 158–163why, one step back
158
159 // express app160 if (fn.handle && fn.set) mount_app = fn;161162 // restore .app property on req and res163 if (mount_app) {

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

lines 164–165why, one step back
164 debug('.use app under %s', path);
165 mount_app.mountpath = path;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 166–176why, one step back
166 fn = function(req, res, next) {
167 var orig = req.app;168 mount_app.handle(req, res, function(err) {169 req.__proto__ = orig.request;170 res.__proto__ = orig.response;171 next(err);172 });173 };174 }175176 this.lazyrouter();

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

line 177why, one step back
177 this._router.use(path, fn);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 178–198why, one step back
178
179 // mounted an app180 if (mount_app) {181 mount_app.parent = this;182 mount_app.emit('mount', this);183 }184185 return this;186};187188/**189 * Proxy to the app `Router#route()`190 * Returns a new `Route` instance for the _path_.191 *192 * Routes are isolated middleware stacks for specific paths.193 * See the Route api docs for details.194 *195 * @api public196 */197198app.route = function(path){

implement app.route()Roman Shtylmanbefore adoption0719e5f

lines 199–200why, one step back
199 this.lazyrouter();
200 return this._router.route(path);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 201–286why, one step back
201};
202203/**204 * Register the given template engine callback `fn`205 * as `ext`.206 *207 * By default will `require()` the engine based on the208 * file extension. For example if you try to render209 * a "foo.jade" file Express will invoke the following internally:210 *211 * app.engine('jade', require('jade').__express);212 *213 * For engines that do not provide `.__express` out of the box,214 * or if you wish to "map" a different extension to the template engine215 * you may use this method. For example mapping the EJS template engine to216 * ".html" files:217 *218 * app.engine('html', require('ejs').renderFile);219 *220 * In this case EJS provides a `.renderFile()` method with221 * the same signature that Express expects: `(path, options, callback)`,222 * though note that it aliases this method as `ejs.__express` internally223 * so if you're using ".ejs" extensions you dont need to do anything.224 *225 * Some template engines do not follow this convention, the226 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)227 * library was created to map all of node's popular template228 * engines to follow this convention, thus allowing them to229 * work seamlessly within Express.230 *231 * @param {String} ext232 * @param {Function} fn233 * @return {app} for chaining234 * @api public235 */236237app.engine = function(ext, fn){238 if ('function' != typeof fn) throw new Error('callback function required');239 if ('.' != ext[0]) ext = '.' + ext;240 this.engines[ext] = fn;241 return this;242};243244/**245 * Proxy to `Router#param()` with one added api feature. The _name_ parameter246 * can be an array of names.247 *248 * See the Router#param() docs for more details.249 *250 * @param {String|Array} name251 * @param {Function} fn252 * @return {app} for chaining253 * @api public254 */255256app.param = function(name, fn){257 var self = this;258 self.lazyrouter();259260 if (Array.isArray(name)) {261 name.forEach(function(key) {262 self.param(key, fn);263 });264 return this;265 }266267 self._router.param(name, fn);268 return this;269};270271/**272 * Assign `setting` to `val`, or return `setting`'s value.273 *274 * app.set('foo', 'bar');275 * app.get('foo');276 * // => "bar"277 *278 * Mounted servers inherit their parent server's settings.279 *280 * @param {String} setting281 * @param {*} [val]282 * @return {Server} for chaining283 * @api public284 */285286app.set = function(setting, val){

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 287–288why, one step back
287 if (arguments.length === 1) {
288 // app.get(setting)

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 289why, one step back
289 return this.settings[setting];

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 290why, one step back
290 }

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 291why, one step back
291

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 292–293why, one step back
292 // set value
293 this.settings[setting] = val;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 294why, one step back
294

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 295–304why, one step back
295 // trigger matched settings
296 switch (setting) {297 case 'etag':298 debug('compile etag %s', val);299 this.set('etag fn', compileETag(val));300 break;301 case 'trust proxy':302 debug('compile trust proxy %s', val);303 this.set('trust proxy fn', compileTrust(val));304 break;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 305why, one step back
305 }

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 306–307why, one step back
306
307 return this;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 308–397why, one step back
308};
309310/**311 * Return the app's absolute pathname312 * based on the parent(s) that have313 * mounted it.314 *315 * For example if the application was316 * mounted as "/admin", which itself317 * was mounted as "/blog" then the318 * return value would be "/blog/admin".319 *320 * @return {String}321 * @api private322 */323324app.path = function(){325 return this.parent326 ? this.parent.path() + this.mountpath327 : '';328};329330/**331 * Check if `setting` is enabled (truthy).332 *333 * app.enabled('foo')334 * // => false335 *336 * app.enable('foo')337 * app.enabled('foo')338 * // => true339 *340 * @param {String} setting341 * @return {Boolean}342 * @api public343 */344345app.enabled = function(setting){346 return !!this.set(setting);347};348349/**350 * Check if `setting` is disabled.351 *352 * app.disabled('foo')353 * // => true354 *355 * app.enable('foo')356 * app.disabled('foo')357 * // => false358 *359 * @param {String} setting360 * @return {Boolean}361 * @api public362 */363364app.disabled = function(setting){365 return !this.set(setting);366};367368/**369 * Enable `setting`.370 *371 * @param {String} setting372 * @return {app} for chaining373 * @api public374 */375376app.enable = function(setting){377 return this.set(setting, true);378};379380/**381 * Disable `setting`.382 *383 * @param {String} setting384 * @return {app} for chaining385 * @api public386 */387388app.disable = function(setting){389 return this.set(setting, false);390};391392/**393 * Delegate `.VERB(...)` calls to `router.VERB(...)`.394 */395396methods.forEach(function(method){397 app[method] = function(path){

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 399why, one step back
399

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

lines 400–402why, one step back
400 this.lazyrouter();
401402 var route = this._router.route(path);

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 403why, one step back
403 route[method].apply(route, [].slice.call(arguments, 1));

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 404–418why, one step back
404 return this;
405 };406});407408/**409 * Special-cased "all" method, applying the given route `path`,410 * middleware, and callback to _every_ HTTP method.411 *412 * @param {String} path413 * @param {Function} ...414 * @return {app} for chaining415 * @api public416 */417418app.all = function(path){

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

lines 419–421why, one step back
419 this.lazyrouter();
420421 var route = this._router.route(path);

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 422why, one step back
422 var args = [].slice.call(arguments, 1);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 423why, one step back
423 methods.forEach(function(method){

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 424why, one step back
424 route[method].apply(route, args);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 425–431why, one step back
425 });
426427 return this;428};429430// del -> delete alias431

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 432why, one step back
432app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 433–451why, one step back
433
434/**435 * Render the given view `name` name with `options`436 * and a callback accepting an error and the437 * rendered template string.438 *439 * Example:440 *441 * app.render('email', { name: 'Tobi' }, function(err, html){442 * // ...443 * })444 *445 * @param {String} name446 * @param {String|Function} options or fn447 * @param {Function} fn448 * @api public449 */450451app.render = function(name, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 452–455why, one step back
452 var opts = {};
453 var cache = this.cache;454 var engines = this.engines;455 var view;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 456–529why, one step back
456
457 // support callback function as second arg458 if ('function' == typeof options) {459 fn = options, options = {};460 }461462 // merge app.locals463 mixin(opts, this.locals);464465 // merge options._locals466 if (options._locals) mixin(opts, options._locals);467468 // merge options469 mixin(opts, options);470471 // set .cache unless explicitly provided472 opts.cache = null == opts.cache473 ? this.enabled('view cache')474 : opts.cache;475476 // primed cache477 if (opts.cache) view = cache[name];478479 // view480 if (!view) {481 view = new (this.get('view'))(name, {482 defaultEngine: this.get('view engine'),483 root: this.get('views'),484 engines: engines485 });486487 if (!view.path) {488 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');489 err.view = view;490 return fn(err);491 }492493 // prime the cache494 if (opts.cache) cache[name] = view;495 }496497 // render498 try {499 view.render(opts, fn);500 } catch (err) {501 fn(err);502 }503};504505/**506 * Listen for connections.507 *508 * A node `http.Server` is returned, with this509 * application (which is a `Function`) as its510 * callback. If you wish to create both an HTTP511 * and HTTPS server you may do so with the "http"512 * and "https" modules as shown here:513 *514 * var http = require('http')515 * , https = require('https')516 * , express = require('express')517 * , app = express();518 *519 * http.createServer(app).listen(80);520 * https.createServer({ ... }, app).listen(443);521 *522 * @return {http.Server}523 * @api public524 */525526app.listen = function(){527 var server = http.createServer(this);528 return server.listen.apply(server, arguments);529};

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 530–540why, one step back
530
531/**532* Log error using console.error.533*534* @param {Error} err535* @api public536*/537538function logerror(err){539 if (this.get('env') !== 'test') console.error(err.stack || err.toString());540}