Skip to content
Myr

application.js

This file

Path

lib/application.js

539 lines · 11.9 KiB · JavaScript

Last changed by

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

History of this file

Take it

The walk stopped after 200 commits: lines older than 78d9c98 point at it.

update connectTJ Holowaychukbefore adoption78d9c98

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

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

line 5why, one step back
5var mixin = require('utils-merge')

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 6why, one step back
6 , escapeHtml = require('escape-html')

update connectTJ Holowaychukbefore adoption78d9c98

lines 7–8why, one step back
7 , Router = require('./router')
8 , methods = require('methods')

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

lines 9–10why, one step back
9 , middleware = require('./middleware/init')
10 , query = require('./middleware/query')

update connectTJ Holowaychukbefore adoption78d9c98

lines 11–12why, one step back
11 , debug = require('debug')('express:application')
12 , View = require('./view')

lint: remove unused stuffJonathan Ongbefore adoption9bed2b8

line 13why, one step back
13 , http = require('http');

update connectTJ Holowaychukbefore adoption78d9c98

lines 14–46why, one step back
14
15/**16 * Application prototype.17 */1819var app = exports = module.exports = {};2021/**22 * Initialize the server.23 *24 * - setup default configuration25 * - setup default middleware26 * - setup route reflection methods27 *28 * @api private29 */3031app.init = function(){32 this.cache = {};33 this.settings = {};34 this.engines = {};35 this.defaultConfiguration();36};3738/**39 * Initialize application configuration.40 *41 * @api private42 */4344app.defaultConfiguration = function(){45 // default settings46 this.enable('x-powered-by');

Merge pull request #1694 from kavu/add_disable_etagTJ Holowaychukbefore adoption610e172

line 47why, one step back
47 this.enable('etag');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 48–49why, one step back
48 var env = process.env.NODE_ENV || 'development';
49 this.set('env', env);

update connectTJ Holowaychukbefore adoption78d9c98

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 52why, one step back
52 debug('booting in %s mode', env);

update connectTJ Holowaychukbefore adoption78d9c98

lines 53–58why, one step back
53
54 // inherit protos55 this.on('mount', function(parent){56 this.request.__proto__ = parent.request;57 this.response.__proto__ = parent.response;58 this.engines.__proto__ = parent.engines;

Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da

line 59why, one step back
59 this.settings.__proto__ = parent.settings;

update connectTJ Holowaychukbefore adoption78d9c98

lines 60–62why, one step back
60 });
6162 // setup locals

Merge pull request #1908 from visionmedia/locals-objectRoman Shtylmanbefore adoption991c2a9

line 63why, one step back
63 this.locals = Object.create(null);

update connectTJ Holowaychukbefore adoption78d9c98

line 64why, one step back
64

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 65–67why, one step back
65 // top-most app is mounted at /
66 this.mountpath = '/';67

update connectTJ Holowaychukbefore adoption78d9c98

lines 68–71why, one step back
68 // default locals
69 this.locals.settings = this.settings;7071 // default configuration

add "view" constructor setting to override view behaviourCaridy Patinobefore adoption0b4e2df

line 72why, one step back
72 this.set('view', View);

update connectTJ Holowaychukbefore adoption78d9c98

lines 73–75why, one step back
73 this.set('views', process.cwd() + '/views');
74 this.set('jsonp callback name', 'callback');75

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 76why, one step back
76 if (env === 'production') {

update connectTJ Holowaychukbefore adoption78d9c98

line 77why, one step back
77 this.enable('view cache');

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 78why, one step back
78 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 79–84why, one step back
79
80 Object.defineProperty(this, 'router', {81 get: function() {82 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.');83 }84 });

update connectTJ Holowaychukbefore adoption78d9c98

lines 85–87why, one step back
85};
8687/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 88why, one step back
88 * lazily adds the base router if it has not yet been added.

update connectTJ Holowaychukbefore adoption78d9c98

line 89why, one step back
89 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 90–101why, one step back
90 * We cannot add the base router in the defaultConfiguration because
91 * it reads app settings which might be set after that has run.92 *93 * @api private94 */95app.lazyrouter = function() {96 if (!this._router) {97 this._router = new Router({98 caseSensitive: this.enabled('case sensitive routing'),99 strict: this.enabled('strict routing')100 });101

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 103–164why, one step back
103 this._router.use(middleware.init(this));
104 }105};106107/**108 * Dispatch a req, res pair into the application. Starts pipeline processing.109 *110 * If no _done_ callback is provided, then default error handlers will respond111 * in the event of an error bubbling through the stack.112 *113 * @api private114 */115116app.handle = function(req, res, done) {117 var env = this.get('env');118119 this._router.handle(req, res, function(err) {120 if (done) {121 return done(err);122 }123124 // unhandled error125 if (err) {126 // default to 500127 if (res.statusCode < 400) res.statusCode = 500;128 debug('default %s', res.statusCode);129130 // respect err.status131 if (err.status) res.statusCode = err.status;132133 // production gets a basic error message134 var msg = 'production' == env135 ? http.STATUS_CODES[res.statusCode]136 : err.stack || err.toString();137 msg = escapeHtml(msg);138139 // log to stderr in a non-test env140 if ('test' != env) console.error(err.stack || err.toString());141 if (res.headerSent) return req.socket.destroy();142 res.setHeader('Content-Type', 'text/html');143 res.setHeader('Content-Length', Buffer.byteLength(msg));144 if ('HEAD' == req.method) return res.end();145 res.end(msg);146 return;147 }148149 // 404150 debug('default 404');151 res.statusCode = 404;152 res.setHeader('Content-Type', 'text/html');153 if ('HEAD' == req.method) return res.end();154 res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');155 });156};157158/**159 * Proxy `Router#use()` to add middleware to the app router.160 * See Router#use() documentation for details.161 *162 * If the _fn_ parameter is an express app, then it will be163 * mounted at the _route_ specified.164 *

update connectTJ Holowaychukbefore adoption78d9c98

lines 165–171why, one step back
165 * @param {String|Function|Server} route
166 * @param {Function|Server} fn167 * @return {app} for chaining168 * @api public169 */170171app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 172why, one step back
172 var mount_app;

update connectTJ Holowaychukbefore adoption78d9c98

lines 173–177why, one step back
173
174 // default route to '/'175 if ('string' != typeof route) fn = route, route = '/';176177 // express app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 178why, one step back
178 if (fn.handle && fn.set) mount_app = fn;

update connectTJ Holowaychukbefore adoption78d9c98

lines 179–180why, one step back
179
180 // restore .app property on req and res

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 181–183why, one step back
181 if (mount_app) {
182 debug('.use app under %s', route);183 mount_app.mountpath = route;

update connectTJ Holowaychukbefore adoption78d9c98

lines 184–185why, one step back
184 fn = function(req, res, next) {
185 var orig = req.app;

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 186why, one step back
186 mount_app.handle(req, res, function(err) {

update connectTJ Holowaychukbefore adoption78d9c98

lines 187–193why, one step back
187 req.__proto__ = orig.request;
188 res.__proto__ = orig.response;189 next(err);190 });191 };192 }193

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 194–195why, one step back
194 this.lazyrouter();
195 this._router.use(route, fn);

update connectTJ Holowaychukbefore adoption78d9c98

lines 196–197why, one step back
196
197 // mounted an app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 198–200why, one step back
198 if (mount_app) {
199 mount_app.parent = this;200 mount_app.emit('mount', this);

update connectTJ Holowaychukbefore adoption78d9c98

lines 201–206why, one step back
201 }
202203 return this;204};205206/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 207–219why, one step back
207 * Proxy to the app `Router#route()`
208 * Returns a new `Route` instance for the _path_.209 *210 * Routes are isolated middleware stacks for specific paths.211 * See the Route api docs for details.212 *213 * @api public214 */215216app.route = function(path){217};218219/**

update connectTJ Holowaychukbefore adoption78d9c98

lines 220–260why, one step back
220 * Register the given template engine callback `fn`
221 * as `ext`.222 *223 * By default will `require()` the engine based on the224 * file extension. For example if you try to render225 * a "foo.jade" file Express will invoke the following internally:226 *227 * app.engine('jade', require('jade').__express);228 *229 * For engines that do not provide `.__express` out of the box,230 * or if you wish to "map" a different extension to the template engine231 * you may use this method. For example mapping the EJS template engine to232 * ".html" files:233 *234 * app.engine('html', require('ejs').renderFile);235 *236 * In this case EJS provides a `.renderFile()` method with237 * the same signature that Express expects: `(path, options, callback)`,238 * though note that it aliases this method as `ejs.__express` internally239 * so if you're using ".ejs" extensions you dont need to do anything.240 *241 * Some template engines do not follow this convention, the242 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)243 * library was created to map all of node's popular template244 * engines to follow this convention, thus allowing them to245 * work seamlessly within Express.246 *247 * @param {String} ext248 * @param {Function} fn249 * @return {app} for chaining250 * @api public251 */252253app.engine = function(ext, fn){254 if ('function' != typeof fn) throw new Error('callback function required');255 if ('.' != ext[0]) ext = '.' + ext;256 this.engines[ext] = fn;257 return this;258};259260/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 261–262why, one step back
261 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
262 * can be an array of names.

update connectTJ Holowaychukbefore adoption78d9c98

line 263why, one step back
263 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 264why, one step back
264 * See the Router#param() docs for more details.

update connectTJ Holowaychukbefore adoption78d9c98

lines 265–272why, one step back
265 *
266 * @param {String|Array} name267 * @param {Function} fn268 * @return {app} for chaining269 * @api public270 */271272app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 273–274why, one step back
273 var self = this;
274 self.lazyrouter();

update connectTJ Holowaychukbefore adoption78d9c98

lines 275–276why, one step back
275
276 if (Array.isArray(name)) {

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 277–278why, one step back
277 name.forEach(function(key) {
278 self.param(key, fn);

update connectTJ Holowaychukbefore adoption78d9c98

line 279why, one step back
279 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 280why, one step back
280 return this;

update connectTJ Holowaychukbefore adoption78d9c98

lines 281–282why, one step back
281 }
282

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 283why, one step back
283 self._router.param(name, fn);

update connectTJ Holowaychukbefore adoption78d9c98

lines 284–296why, one step back
284 return this;
285};286287/**288 * Assign `setting` to `val`, or return `setting`'s value.289 *290 * app.set('foo', 'bar');291 * app.get('foo');292 * // => "bar"293 *294 * Mounted servers inherit their parent server's settings.295 *296 * @param {String} setting

Merge pull request #1890 from oliversalzburg/patch-1TJ Holowaychukbefore adoption827dfed

line 297why, one step back
297 * @param {*} [val]

update connectTJ Holowaychukbefore adoption78d9c98

lines 298–303why, one step back
298 * @return {Server} for chaining
299 * @api public300 */301302app.set = function(setting, val){303 if (1 == arguments.length) {

Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da

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

update connectTJ Holowaychukbefore adoption78d9c98

lines 305–326why, one step back
305 } else {
306 this.settings[setting] = val;307 return this;308 }309};310311/**312 * Return the app's absolute pathname313 * based on the parent(s) that have314 * mounted it.315 *316 * For example if the application was317 * mounted as "/admin", which itself318 * was mounted as "/blog" then the319 * return value would be "/blog/admin".320 *321 * @return {String}322 * @api private323 */324325app.path = function(){326 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 327why, one step back
327 ? this.parent.path() + this.mountpath

update connectTJ Holowaychukbefore adoption78d9c98

lines 328–400why, one step back
328 : '';
329};330331/**332 * Check if `setting` is enabled (truthy).333 *334 * app.enabled('foo')335 * // => false336 *337 * app.enable('foo')338 * app.enabled('foo')339 * // => true340 *341 * @param {String} setting342 * @return {Boolean}343 * @api public344 */345346app.enabled = function(setting){347 return !!this.set(setting);348};349350/**351 * Check if `setting` is disabled.352 *353 * app.disabled('foo')354 * // => true355 *356 * app.enable('foo')357 * app.disabled('foo')358 * // => false359 *360 * @param {String} setting361 * @return {Boolean}362 * @api public363 */364365app.disabled = function(setting){366 return !this.set(setting);367};368369/**370 * Enable `setting`.371 *372 * @param {String} setting373 * @return {app} for chaining374 * @api public375 */376377app.enable = function(setting){378 return this.set(setting, true);379};380381/**382 * Disable `setting`.383 *384 * @param {String} setting385 * @return {app} for chaining386 * @api public387 */388389app.disable = function(setting){390 return this.set(setting, false);391};392393/**394 * Delegate `.VERB(...)` calls to `router.VERB(...)`.395 */396397methods.forEach(function(method){398 app[method] = function(path){399 if ('get' == method && 1 == arguments.length) return this.set(path);400

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 401–402why, one step back
401 this.lazyrouter();
402

add app.VERB() paths array deprecation warningTJ Holowaychukbefore adoption91c71d6

lines 403–407why, one step back
403 // deprecated
404 if (Array.isArray(path)) {405 console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');406 }407

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 408–411why, one step back
408 var route = this._router.route(path);
409 for (var i=1 ; i<arguments.length ; ++i) {410 route[method](arguments[i]);411 }

update connectTJ Holowaychukbefore adoption78d9c98

lines 412–426why, one step back
412 return this;
413 };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){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 427–429why, one step back
427 this.lazyrouter();
428429 var route = this._router.route(path);

update connectTJ Holowaychukbefore adoption78d9c98

lines 430–431why, one step back
430 var args = arguments;
431 methods.forEach(function(method){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 432–436why, one step back
432 for (var i=1 ; i<args.length ; ++i) {
433 route[method](args[i]);434 }435 });436

update connectTJ Holowaychukbefore adoption78d9c98

lines 437–472why, one step back
437 return this;
438};439440// del -> delete alias441442app.del = app.delete;443444/**445 * Render the given view `name` name with `options`446 * and a callback accepting an error and the447 * rendered template string.448 *449 * Example:450 *451 * app.render('email', { name: 'Tobi' }, function(err, html){452 * // ...453 * })454 *455 * @param {String} name456 * @param {String|Function} options or fn457 * @param {Function} fn458 * @api public459 */460461app.render = function(name, options, fn){462 var opts = {}463 , cache = this.cache464 , engines = this.engines465 , view;466467 // support callback function as second arg468 if ('function' == typeof options) {469 fn = options, options = {};470 }471472 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 473why, one step back
473 mixin(opts, this.locals);

update connectTJ Holowaychukbefore adoption78d9c98

lines 474–475why, one step back
474
475 // merge options._locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 476why, one step back
476 if (options._locals) mixin(opts, options._locals);

update connectTJ Holowaychukbefore adoption78d9c98

lines 477–478why, one step back
477
478 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 479why, one step back
479 mixin(opts, options);

update connectTJ Holowaychukbefore adoption78d9c98

lines 480–490why, one step back
480
481 // set .cache unless explicitly provided482 opts.cache = null == opts.cache483 ? this.enabled('view cache')484 : opts.cache;485486 // primed cache487 if (opts.cache) view = cache[name];488489 // view490 if (!view) {

add "view" constructor setting to override view behaviourCaridy Patinobefore adoption0b4e2df

line 491why, one step back
491 view = new (this.get('view'))(name, {

update connectTJ Holowaychukbefore adoption78d9c98

lines 492–497why, one step back
492 defaultEngine: this.get('view engine'),
493 root: this.get('views'),494 engines: engines495 });496497 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

line 498why, one step back
498 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');

update connectTJ Holowaychukbefore adoption78d9c98

lines 499–539why, one step back
499 err.view = view;
500 return fn(err);501 }502503 // prime the cache504 if (opts.cache) cache[name] = view;505 }506507 // render508 try {509 view.render(opts, fn);510 } catch (err) {511 fn(err);512 }513};514515/**516 * Listen for connections.517 *518 * A node `http.Server` is returned, with this519 * application (which is a `Function`) as its520 * callback. If you wish to create both an HTTP521 * and HTTPS server you may do so with the "http"522 * and "https" modules as shown here:523 *524 * var http = require('http')525 * , https = require('https')526 * , express = require('express')527 * , app = express();528 *529 * http.createServer(app).listen(80);530 * https.createServer({ ... }, app).listen(443);531 *532 * @return {http.Server}533 * @api public534 */535536app.listen = function(){537 var server = http.createServer(this);538 return server.listen.apply(server, arguments);539};