Skip to content
Myr

application.js

This file

Path

lib/application.js

589 lines · 12.3 KiB · JavaScript

Last changed by

docsTj Holowaychukbefore adoption2e22887

History of this file

Take it

application.jsTj Holowaychukbefore adoptiond0585bd

lines 1–16why, one step back
1
2/*!3 * Express - proto4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var connect = require('connect')13 , Router = require('./router')14 , toArray = require('./utils').toArray15 , methods = Router.methods.concat('del', 'all')16 , res = require('./response')

new ViewTj Holowaychukbefore adoptione1da383

line 17why, one step back
17 , View = require('./view')

application.jsTj Holowaychukbefore adoptiond0585bd

lines 18–33why, one step back
18 , url = require('url')
19 , utils = connect.utils20 , path = require('path')21 , join = path.join22 , fs = require('fs')23 , qs = require('qs');2425/**26 * Expose `HTTPServer`.27 */2829var app = exports = module.exports = {};3031/**32 * Initialize the server.33 *

refactoring boot logicTj Holowaychukbefore adoption8848004

lines 34–37why, one step back
34 * - setup default configuration
35 * - setup default middleware36 * - setup route reflection methods37 *

application.jsTj Holowaychukbefore adoptiond0585bd

lines 38–40why, one step back
38 * @api private
39 */40

refactoring boot logicTj Holowaychukbefore adoption8848004

line 41why, one step back
41app.init = function(){

application.jsTj Holowaychukbefore adoptiond0585bd

line 42why, one step back
42 var self = this;

app.lookup()Tj Holowaychukbefore adoption76b7d69

line 43why, one step back
43 this.cache = {};

application.jsTj Holowaychukbefore adoptiond0585bd

line 44why, one step back
44 this.settings = {};

added app.register()Tj Holowaychukbefore adoptiona9396ef

line 45why, one step back
45 this.engines = {};

application.jsTj Holowaychukbefore adoptiond0585bd

lines 46–47why, one step back
46 this.redirects = {};
47 this.isCallbacks = {};

app.locals.use(fn)Tj Holowaychukbefore adoption0f6ad43

line 48why, one step back
48 this.viewCallbacks = [];

refactoring boot logicTj Holowaychukbefore adoption8848004

line 49why, one step back
49 this.defaultConfiguration();

application.jsTj Holowaychukbefore adoptiond0585bd

line 50why, one step back
50

miscTj Holowaychukbefore adoptiond4b08e9

line 51why, one step back
51 // route reflection methods

refactoring boot logicTj Holowaychukbefore adoption8848004

lines 52–53why, one step back
52 methods.forEach(function(method){
53 self.lookup[method] = function(path){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 54why, one step back
54 return self._router.lookup(method, path);

refactoring boot logicTj Holowaychukbefore adoption8848004

lines 55–57why, one step back
55 };
5657 self.match[method] = function(path){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 58why, one step back
58 return self._router.match(method, path);

refactoring boot logicTj Holowaychukbefore adoption8848004

lines 59–61why, one step back
59 };
6061 self.remove[method] = function(path){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 62why, one step back
62 return self._router.lookup(method, path).remove();

refactoring boot logicTj Holowaychukbefore adoption8848004

lines 63–80why, one step back
63 };
64 });6566 // del -> delete67 self.lookup.del = self.lookup.delete;68 self.match.del = self.match.delete;69 self.remove.del = self.remove.delete;70};7172/**73 * Initialize application configuration.74 *75 * @api private76 */7778app.defaultConfiguration = function(){79 var self = this;80

req.query is always presentTj Holowaychukbefore adoptiond1ce4c9

line 81why, one step back
81 // default settings

Fixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4

line 82why, one step back
82 this.set('root', '/');

application.jsTj Holowaychukbefore adoptiond0585bd

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

req.query is always presentTj Holowaychukbefore adoptiond1ce4c9

lines 84–85why, one step back
84
85 // always parse req.query

application.jsTj Holowaychukbefore adoptiond0585bd

lines 86–88why, one step back
86 this.use(connect.query());
8788 this.locals = function(obj){

misc refactoringTj Holowaychukbefore adoption4ed92d5

line 89why, one step back
89 for (var key in obj) self.locals[key] = obj[key];

application.jsTj Holowaychukbefore adoptiond0585bd

line 90why, one step back
90 return self;

app.locals.use(fn)Tj Holowaychukbefore adoption0f6ad43

lines 91–93why, one step back
91 };
9293 this.locals.use = function(fn){

added sync signature for app.locals.use()Tj Holowaychukbefore adoption965e1d6

lines 94–101why, one step back
94 if (3 == fn.length) {
95 self.viewCallbacks.push(fn);96 } else {97 self.viewCallbacks.push(function(req, res, done){98 fn(req, res);99 done();100 });101 }

app.locals.use(fn)Tj Holowaychukbefore adoption0f6ad43

line 102why, one step back
102 return this;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 103–114why, one step back
103 };
104105 // expose objects to each other106 this.use(function(req, res, next){107 var charset;108 res.setHeader('X-Powered-By', 'Express');109 req.app = res.app = self;110 req.res = res;111 res.req = req;112 req.next = next;113114 res.locals = function(obj){

misc refactoringTj Holowaychukbefore adoption4ed92d5

line 115why, one step back
115 for (var key in obj) res.locals[key] = obj[key];

application.jsTj Holowaychukbefore adoptiond0585bd

lines 116–122why, one step back
116 return res;
117 };118119 next();120 });121122 // router

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

lines 123–124why, one step back
123 this._router = new Router(this);
124 this.routes = this._router.routes;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 125–126why, one step back
125 this.__defineGetter__('router', function(){
126 this.__usedRouter = true;

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 127why, one step back
127 return self._router.middleware;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 128–147why, one step back
128 });
129130 // default locals131 this.locals.settings = this.settings;132133 // default production configuration134 this.configure('production', function(){135 this.enable('view cache');136 });137};138139/**140 * Remove routes matching the given `path`.141 *142 * @param {Route} path143 * @return {Boolean}144 * @api public145 */146147app.remove = function(path){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 148why, one step back
148 return this._router.lookup('all', path).remove();

application.jsTj Holowaychukbefore adoptiond0585bd

lines 149–160why, one step back
149};
150151/**152 * Lookup routes defined with a path153 * equivalent to `path`.154 *155 * @param {Stirng} path156 * @return {Array}157 * @api public158 */159160app.lookup = function(path){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 161why, one step back
161 return this._router.lookup('all', path);

application.jsTj Holowaychukbefore adoptiond0585bd

lines 162–172why, one step back
162};
163164/**165 * Lookup routes matching the given `url`.166 *167 * @param {Stirng} url168 * @return {Array}169 * @api public170 */171172app.match = function(url){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 173why, one step back
173 return this._router.match('all', url);

application.jsTj Holowaychukbefore adoptiond0585bd

lines 174–176why, one step back
174};
175176/**

docsTj Holowaychukbefore adoption2e22887

line 177why, one step back
177 * Proxy `connect#use()` to apply settings to

application.jsTj Holowaychukbefore adoptiond0585bd

lines 178–212why, one step back
178 * mounted applications.
179 *180 * @param {String|Function|Server} route181 * @param {Function|Server} middleware182 * @return {Server} for chaining183 * @api public184 */185186app.use = function(route, middleware){187 var app, home, handle;188189 if ('string' != typeof route) {190 middleware = route, route = '/';191 }192193 // express app194 if (middleware.handle && middleware.set) app = middleware;195196 // restore .app property on req and res197 if (app) {198 app.route = route;199 middleware = function(req, res, next) {200 var orig = req.app;201 app.handle(req, res, function(err){202 req.app = res.app = orig;203 next(err);204 });205 };206 }207208 connect.proto.use.call(this, route, middleware);209210 // mounted an app, invoke the hook211 // and adjust some settings212 if (app) {

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

lines 213–216why, one step back
213 var root = this.get('root') || this.route;
214 if ('/' == root) root = '';215 root = root + (app.get('root') || app.route);216 app.set('root', root);

application.jsTj Holowaychukbefore adoptiond0585bd

lines 217–250why, one step back
217 app.parent = this;
218 if (app.__mounted) app.__mounted.call(app, this);219 }220221 return this;222};223224/**225 * Assign a callback `fn` which is called226 * when this `Server` is passed to `Server#use()`.227 *228 * Examples:229 *230 * var app = express.createServer()231 * , blog = express.createServer();232 *233 * blog.mounted(function(parent){234 * // parent is app235 * // "this" is blog236 * });237 *238 * app.use(blog);239 *240 * @param {Function} fn241 * @return {Server} for chaining242 * @api public243 */244245app.mounted = function(fn){246 this.__mounted = fn;247 return this;248};249250/**

added app.register()Tj Holowaychukbefore adoptiona9396ef

lines 251–253why, one step back
251 * Register the given template engine callback `fn`
252 * as `ext`. For example we may wish to map ".html"253 * files to ejs rather than using the ".ejs" extension.

application.jsTj Holowaychukbefore adoptiond0585bd

line 254why, one step back
254 *

added app.register()Tj Holowaychukbefore adoptiona9396ef

lines 255–262why, one step back
255 * app.register('.html', require('ejs').render);
256 *257 * or258 *259 * app.register('html', require('ejs').render);260 *261 * @param {String} ext262 * @param {Function} fn

application.jsTj Holowaychukbefore adoptiond0585bd

lines 263–266why, one step back
263 * @return {Server} for chaining
264 * @api public265 */266

added app.register()Tj Holowaychukbefore adoptiona9396ef

lines 267–269why, one step back
267app.register = function(ext, fn){
268 if ('.' != ext[0]) ext = '.' + ext;269 this.engines[ext] = fn;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 270–344why, one step back
270 return this;
271};272273/**274 * Map the given param placeholder `name`(s) to the given callback(s).275 *276 * Param mapping is used to provide pre-conditions to routes277 * which us normalized placeholders. This callback has the same278 * signature as regular middleware, for example below when ":userId"279 * is used this function will be invoked in an attempt to load the user.280 *281 * app.param('userId', function(req, res, next, id){282 * User.find(id, function(err, user){283 * if (err) {284 * next(err);285 * } else if (user) {286 * req.user = user;287 * next();288 * } else {289 * next(new Error('failed to load user'));290 * }291 * });292 * });293 *294 * Passing a single function allows you to map logic295 * to the values passed to `app.param()`, for example296 * this is useful to provide coercion support in a concise manner.297 *298 * The following example maps regular expressions to param values299 * ensuring that they match, otherwise passing control to the next300 * route:301 *302 * app.param(function(name, regexp){303 * if (regexp instanceof RegExp) {304 * return function(req, res, next, val){305 * var captures;306 * if (captures = regexp.exec(String(val))) {307 * req.params[name] = captures;308 * next();309 * } else {310 * next('route');311 * }312 * }313 * }314 * });315 *316 * We can now use it as shown below, where "/commit/:commit" expects317 * that the value for ":commit" is at 5 or more digits. The capture318 * groups are then available as `req.params.commit` as we defined319 * in the function above.320 *321 * app.param('commit', /^\d{5,}$/);322 *323 * For more of this useful functionality take a look324 * at [express-params](http://github.com/visionmedia/express-params).325 *326 * @param {String|Array|Function} name327 * @param {Function} fn328 * @return {Server} for chaining329 * @api public330 */331332app.param = function(name, fn){333 var self = this334 , fns = [].slice.call(arguments, 1);335336 // array337 if (Array.isArray(name)) {338 name.forEach(function(name){339 fns.forEach(function(fn){340 self.param(name, fn);341 });342 });343 // param logic344 } else if ('function' == typeof name) {

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

line 345why, one step back
345 this._router.param(name);

application.jsTj Holowaychukbefore adoptiond0585bd

lines 346–349why, one step back
346 // single
347 } else {348 if (':' == name[0]) name = name.substr(1);349 fns.forEach(function(fn){

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 351–497why, one step back
351 });
352 }353354 return this;355};356357/**358 * Register the given callback `fn` for the given `type`.359 *360 * @param {String} type361 * @param {Function} fn362 * @return {Server} for chaining363 * @api public364 */365366app.is = function(type, fn){367 if (!fn) return this.isCallbacks[type];368 this.isCallbacks[type] = fn;369 return this;370};371372/**373 * Assign `setting` to `val`, or return `setting`'s value.374 * Mounted servers inherit their parent server's settings.375 *376 * @param {String} setting377 * @param {String} val378 * @return {Server|Mixed} for chaining, or the setting value379 * @api public380 */381382app.set = function(setting, val){383 if (val === undefined) {384 if (this.settings.hasOwnProperty(setting)) {385 return this.settings[setting];386 } else if (this.parent) {387 return this.parent.set(setting);388 }389 } else {390 this.settings[setting] = val;391 return this;392 }393};394395/**396 * Check if `setting` is enabled.397 *398 * @param {String} setting399 * @return {Boolean}400 * @api public401 */402403app.enabled = function(setting){404 return !!this.set(setting);405};406407/**408 * Check if `setting` is disabled.409 *410 * @param {String} setting411 * @return {Boolean}412 * @api public413 */414415app.disabled = function(setting){416 return !this.set(setting);417};418419/**420 * Enable `setting`.421 *422 * @param {String} setting423 * @return {Server} for chaining424 * @api public425 */426427app.enable = function(setting){428 return this.set(setting, true);429};430431/**432 * Disable `setting`.433 *434 * @param {String} setting435 * @return {Server} for chaining436 * @api public437 */438439app.disable = function(setting){440 return this.set(setting, false);441};442443/**444 * Redirect `key` to `url`.445 *446 * @param {String} key447 * @param {String} url448 * @return {Server} for chaining449 * @api public450 */451452app.redirect = function(key, url){453 this.redirects[key] = url;454 return this;455};456457/**458 * Configure callback for zero or more envs,459 * when no env is specified that callback will460 * be invoked for all environments. Any combination461 * can be used multiple times, in any order desired.462 *463 * Examples:464 *465 * app.configure(function(){466 * // executed for all envs467 * });468 *469 * app.configure('stage', function(){470 * // executed staging env471 * });472 *473 * app.configure('stage', 'production', function(){474 * // executed for stage and production475 * });476 *477 * @param {String} env...478 * @param {Function} fn479 * @return {Server} for chaining480 * @api public481 */482483app.configure = function(env, fn){484 var envs = 'all'485 , args = toArray(arguments);486 fn = args.pop();487 if (args.length) envs = args;488 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);489 return this;490};491492/**493 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.494 */495496methods.forEach(function(method){497 app[method] = function(path){

Added `app.get(setting)`. Closes #842Tj Holowaychukbefore adoptione0bd0d6

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 499why, one step back
499 var args = [method].concat(toArray(arguments));

Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc

lines 500–501why, one step back
500 if (!this.__usedRouter) this.use(this._router);
501 return this._router._route.apply(this._router, args);

application.jsTj Holowaychukbefore adoptiond0585bd

lines 502–528why, one step back
502 }
503});504505/**506 * Special-cased "all" method, applying the given route `path`,507 * middleware, and callback to _every_ HTTP method.508 *509 * @param {String} path510 * @param {Function} ...511 * @return {Server} for chaining512 * @api public513 */514515app.all = function(path){516 var args = arguments;517 methods.forEach(function(method){518 if ('all' == method) return;519 app[method].apply(this, args);520 }, this);521 return this;522};523524// del -> delete alias525526app.del = app.delete;527528/**

new ViewTj Holowaychukbefore adoptione1da383

line 529why, one step back
529 * Render the given view `name` name with `options`

application.jsTj Holowaychukbefore adoptiond0585bd

lines 530–532why, one step back
530 * and a callback accepting an error and the
531 * rendered template string.532 *

new ViewTj Holowaychukbefore adoptione1da383

line 533why, one step back
533 * @param {String} name

misc refactoringTj Holowaychukbefore adoption294bc8c

line 534why, one step back
534 * @param {String|Function} options or fn

application.jsTj Holowaychukbefore adoptiond0585bd

lines 535–538why, one step back
535 * @param {Function} fn
536 * @api public537 */538

new ViewTj Holowaychukbefore adoptione1da383

line 539why, one step back
539app.render = function(name, options, fn){

application.jsTj Holowaychukbefore adoptiond0585bd

line 540why, one step back
540 var self = this

merging res.localsTj Holowaychukbefore adoption98e2c05

line 541why, one step back
541 , opts = {}

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

line 542why, one step back
542 , cache = this.cache

new ViewTj Holowaychukbefore adoptione1da383

lines 543–544why, one step back
543 , engines = this.engines
544 , view;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 545–546why, one step back
545
546 // support callback function as second arg

misc refactoringTj Holowaychukbefore adoption294bc8c

lines 547–548why, one step back
547 if ('function' == typeof options) {
548 fn = options, options = {};

application.jsTj Holowaychukbefore adoptiond0585bd

lines 549–551why, one step back
549 }
550551 // merge app.locals

merging res.localsTj Holowaychukbefore adoption98e2c05

line 552why, one step back
552 utils.merge(opts, this.locals);

application.jsTj Holowaychukbefore adoptiond0585bd

line 553why, one step back
553

merging res.localsTj Holowaychukbefore adoption98e2c05

lines 554–562why, one step back
554 // merge options.locals
555 if (options.locals) {556 utils.merge(opts, options.locals);557 delete opts.locals;558 }559560 // merge options561 utils.merge(opts, options);562

new ViewTj Holowaychukbefore adoptione1da383

lines 563–566why, one step back
563 // set .cache unless explicitly provided
564 opts.cache = null == opts.cache565 ? this.enabled('view cache')566 : opts.cache;

application.jsTj Holowaychukbefore adoptiond0585bd

line 567why, one step back
567

new ViewTj Holowaychukbefore adoptione1da383

lines 568–569why, one step back
568 // primed cache
569 if (opts.cache) view = cache[name];

application.jsTj Holowaychukbefore adoptiond0585bd

line 570why, one step back
570

new ViewTj Holowaychukbefore adoptione1da383

lines 571–577why, one step back
571 // view
572 if (!view) {573 view = new View(name, {574 defaultEngine: this.set('view engine')575 , root: this.set('views') || process.cwd() + '/views'576 , engines: engines577 });

application.jsTj Holowaychukbefore adoptiond0585bd

line 578why, one step back
578

new ViewTj Holowaychukbefore adoptione1da383

lines 579–582why, one step back
579 // prime the cache
580 if (opts.cache) cache[name] = view;581 }582

application.jsTj Holowaychukbefore adoptiond0585bd

lines 583–584why, one step back
583 // render
584 try {

new ViewTj Holowaychukbefore adoptione1da383

line 585why, one step back
585 view.render(opts, fn);

application.jsTj Holowaychukbefore adoptiond0585bd

lines 586–589why, one step back
586 } catch (err) {
587 fn(err);588 }589};