Skip to content
Myr

application.js

This file

Path

lib/application.js

594 lines · 12.5 KiB · JavaScript

Last changed by

misc refactoringTj Holowaychukbefore adoption4ed92d5

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 = {};

refactoring boot logicTj Holowaychukbefore adoption8848004

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 49why, one step back
49

refactoring boot logicTj Holowaychukbefore adoption8848004

lines 50–79why, one step back
50 // route manipulation methods
51 methods.forEach(function(method){52 self.lookup[method] = function(path){53 return self.routes.lookup(method, path);54 };5556 self.match[method] = function(path){57 return self.routes.match(method, path);58 };5960 self.remove[method] = function(path){61 return self.routes.lookup(method, path).remove();62 };63 });6465 // del -> delete66 self.lookup.del = self.lookup.delete;67 self.match.del = self.match.delete;68 self.remove.del = self.remove.delete;69};7071/**72 * Initialize application configuration.73 *74 * @api private75 */7677app.defaultConfiguration = function(){78 var self = this;79

req.query is always presentTj Holowaychukbefore adoptiond1ce4c9

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 81–82why, one step back
81 this.set('home', '/');
82 this.set('env', process.env.NODE_ENV || 'development');

req.query is always presentTj Holowaychukbefore adoptiond1ce4c9

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 85–87why, one step back
85 this.use(connect.query());
8687 this.locals = function(obj){

misc refactoringTj Holowaychukbefore adoption4ed92d5

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 89–104why, one step back
89 return self;
90 };9192 // expose objects to each other93 this.use(function(req, res, next){94 var charset;95 res.setHeader('X-Powered-By', 'Express');96 req.app = res.app = self;97 req.res = res;98 res.req = req;99 req.next = next;100101 // charset102 if (charset = self.set('charset')) res.charset = charset;103104 res.locals = function(obj){

misc refactoringTj Holowaychukbefore adoption4ed92d5

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 106–239why, one step back
106 return res;
107 };108109 next();110 });111112 // router113 this.routes = new Router(this);114 this.__defineGetter__('router', function(){115 this.__usedRouter = true;116 return self.routes.middleware;117 });118119 // default locals120 this.locals.settings = this.settings;121122 // default production configuration123 this.configure('production', function(){124 this.enable('view cache');125 });126};127128/**129 * Remove routes matching the given `path`.130 *131 * @param {Route} path132 * @return {Boolean}133 * @api public134 */135136app.remove = function(path){137 return this.routes.lookup('all', path).remove();138};139140/**141 * Lookup routes defined with a path142 * equivalent to `path`.143 *144 * @param {Stirng} path145 * @return {Array}146 * @api public147 */148149app.lookup = function(path){150 return this.routes.lookup('all', path);151};152153/**154 * Lookup routes matching the given `url`.155 *156 * @param {Stirng} url157 * @return {Array}158 * @api public159 */160161app.match = function(url){162 return this.routes.match('all', url);163};164165/**166 * Proxy `connect.HTTPServer#use()` to apply settings to167 * mounted applications.168 *169 * @param {String|Function|Server} route170 * @param {Function|Server} middleware171 * @return {Server} for chaining172 * @api public173 */174175app.use = function(route, middleware){176 var app, home, handle;177178 if ('string' != typeof route) {179 middleware = route, route = '/';180 }181182 // express app183 if (middleware.handle && middleware.set) app = middleware;184185 // restore .app property on req and res186 if (app) {187 app.route = route;188 middleware = function(req, res, next) {189 var orig = req.app;190 app.handle(req, res, function(err){191 req.app = res.app = orig;192 next(err);193 });194 };195 }196197 connect.proto.use.call(this, route, middleware);198199 // mounted an app, invoke the hook200 // and adjust some settings201 if (app) {202 base = this.set('basepath') || this.route;203 if ('/' == base) base = '';204 base = base + (app.set('basepath') || app.route);205 app.set('basepath', base);206 app.parent = this;207 if (app.__mounted) app.__mounted.call(app, this);208 }209210 return this;211};212213/**214 * Assign a callback `fn` which is called215 * when this `Server` is passed to `Server#use()`.216 *217 * Examples:218 *219 * var app = express.createServer()220 * , blog = express.createServer();221 *222 * blog.mounted(function(parent){223 * // parent is app224 * // "this" is blog225 * });226 *227 * app.use(blog);228 *229 * @param {Function} fn230 * @return {Server} for chaining231 * @api public232 */233234app.mounted = function(fn){235 this.__mounted = fn;236 return this;237};238239/**

added app.register()Tj Holowaychukbefore adoptiona9396ef

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 243why, one step back
243 *

added app.register()Tj Holowaychukbefore adoptiona9396ef

lines 244–251why, one step back
244 * app.register('.html', require('ejs').render);
245 *246 * or247 *248 * app.register('html', require('ejs').render);249 *250 * @param {String} ext251 * @param {Function} fn

application.jsTj Holowaychukbefore adoptiond0585bd

lines 252–255why, one step back
252 * @return {Server} for chaining
253 * @api public254 */255

added app.register()Tj Holowaychukbefore adoptiona9396ef

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 259–533why, one step back
259 return this;
260};261262/**263 * Map the given param placeholder `name`(s) to the given callback `fn`.264 * Register the given view helpers `obj`. This method265 * can be called several times to apply additional helpers.266 *267 * @param {Object} obj268 * @return {Server} for chaining269 * @api public270 */271272app.locals = function(obj){273 utils.merge(this._locals, obj);274 return this;275};276277/**278 * Map the given param placeholder `name`(s) to the given callback(s).279 *280 * Param mapping is used to provide pre-conditions to routes281 * which us normalized placeholders. This callback has the same282 * signature as regular middleware, for example below when ":userId"283 * is used this function will be invoked in an attempt to load the user.284 *285 * app.param('userId', function(req, res, next, id){286 * User.find(id, function(err, user){287 * if (err) {288 * next(err);289 * } else if (user) {290 * req.user = user;291 * next();292 * } else {293 * next(new Error('failed to load user'));294 * }295 * });296 * });297 *298 * Passing a single function allows you to map logic299 * to the values passed to `app.param()`, for example300 * this is useful to provide coercion support in a concise manner.301 *302 * The following example maps regular expressions to param values303 * ensuring that they match, otherwise passing control to the next304 * route:305 *306 * app.param(function(name, regexp){307 * if (regexp instanceof RegExp) {308 * return function(req, res, next, val){309 * var captures;310 * if (captures = regexp.exec(String(val))) {311 * req.params[name] = captures;312 * next();313 * } else {314 * next('route');315 * }316 * }317 * }318 * });319 *320 * We can now use it as shown below, where "/commit/:commit" expects321 * that the value for ":commit" is at 5 or more digits. The capture322 * groups are then available as `req.params.commit` as we defined323 * in the function above.324 *325 * app.param('commit', /^\d{5,}$/);326 *327 * For more of this useful functionality take a look328 * at [express-params](http://github.com/visionmedia/express-params).329 *330 * @param {String|Array|Function} name331 * @param {Function} fn332 * @return {Server} for chaining333 * @api public334 */335336app.param = function(name, fn){337 var self = this338 , fns = [].slice.call(arguments, 1);339340 // array341 if (Array.isArray(name)) {342 name.forEach(function(name){343 fns.forEach(function(fn){344 self.param(name, fn);345 });346 });347 // param logic348 } else if ('function' == typeof name) {349 this.routes.param(name);350 // single351 } else {352 if (':' == name[0]) name = name.substr(1);353 fns.forEach(function(fn){354 self.routes.param(name, fn);355 });356 }357358 return this;359};360361/**362 * Register the given callback `fn` for the given `type`.363 *364 * @param {String} type365 * @param {Function} fn366 * @return {Server} for chaining367 * @api public368 */369370app.is = function(type, fn){371 if (!fn) return this.isCallbacks[type];372 this.isCallbacks[type] = fn;373 return this;374};375376/**377 * Assign `setting` to `val`, or return `setting`'s value.378 * Mounted servers inherit their parent server's settings.379 *380 * @param {String} setting381 * @param {String} val382 * @return {Server|Mixed} for chaining, or the setting value383 * @api public384 */385386app.set = function(setting, val){387 if (val === undefined) {388 if (this.settings.hasOwnProperty(setting)) {389 return this.settings[setting];390 } else if (this.parent) {391 return this.parent.set(setting);392 }393 } else {394 this.settings[setting] = val;395 return this;396 }397};398399/**400 * Check if `setting` is enabled.401 *402 * @param {String} setting403 * @return {Boolean}404 * @api public405 */406407app.enabled = function(setting){408 return !!this.set(setting);409};410411/**412 * Check if `setting` is disabled.413 *414 * @param {String} setting415 * @return {Boolean}416 * @api public417 */418419app.disabled = function(setting){420 return !this.set(setting);421};422423/**424 * Enable `setting`.425 *426 * @param {String} setting427 * @return {Server} for chaining428 * @api public429 */430431app.enable = function(setting){432 return this.set(setting, true);433};434435/**436 * Disable `setting`.437 *438 * @param {String} setting439 * @return {Server} for chaining440 * @api public441 */442443app.disable = function(setting){444 return this.set(setting, false);445};446447/**448 * Redirect `key` to `url`.449 *450 * @param {String} key451 * @param {String} url452 * @return {Server} for chaining453 * @api public454 */455456app.redirect = function(key, url){457 this.redirects[key] = url;458 return this;459};460461/**462 * Configure callback for zero or more envs,463 * when no env is specified that callback will464 * be invoked for all environments. Any combination465 * can be used multiple times, in any order desired.466 *467 * Examples:468 *469 * app.configure(function(){470 * // executed for all envs471 * });472 *473 * app.configure('stage', function(){474 * // executed staging env475 * });476 *477 * app.configure('stage', 'production', function(){478 * // executed for stage and production479 * });480 *481 * @param {String} env...482 * @param {Function} fn483 * @return {Server} for chaining484 * @api public485 */486487app.configure = function(env, fn){488 var envs = 'all'489 , args = toArray(arguments);490 fn = args.pop();491 if (args.length) envs = args;492 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);493 return this;494};495496/**497 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.498 */499500methods.forEach(function(method){501 app[method] = function(path){502 if (1 == arguments.length) return this.routes.lookup(method, path);503 var args = [method].concat(toArray(arguments));504 if (!this.__usedRouter) this.use(this.router);505 return this.routes._route.apply(this.routes, args);506 }507});508509/**510 * Special-cased "all" method, applying the given route `path`,511 * middleware, and callback to _every_ HTTP method.512 *513 * @param {String} path514 * @param {Function} ...515 * @return {Server} for chaining516 * @api public517 */518519app.all = function(path){520 var args = arguments;521 if (1 == args.length) return this.routes.lookup('all', path);522 methods.forEach(function(method){523 if ('all' == method) return;524 app[method].apply(this, args);525 }, this);526 return this;527};528529// del -> delete alias530531app.del = app.delete;532533/**

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 535–537why, one step back
535 * and a callback accepting an error and the
536 * rendered template string.537 *

new ViewTj Holowaychukbefore adoptione1da383

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

misc refactoringTj Holowaychukbefore adoption294bc8c

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 540–543why, one step back
540 * @param {Function} fn
541 * @api public542 */543

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

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

merging res.localsTj Holowaychukbefore adoption98e2c05

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

new ViewTj Holowaychukbefore adoptione1da383

lines 548–549why, one step back
548 , engines = this.engines
549 , view;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 550–551why, one step back
550
551 // support callback function as second arg

misc refactoringTj Holowaychukbefore adoption294bc8c

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 554–556why, one step back
554 }
555556 // merge app.locals

merging res.localsTj Holowaychukbefore adoption98e2c05

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 558why, one step back
558

merging res.localsTj Holowaychukbefore adoption98e2c05

lines 559–567why, one step back
559 // merge options.locals
560 if (options.locals) {561 utils.merge(opts, options.locals);562 delete opts.locals;563 }564565 // merge options566 utils.merge(opts, options);567

new ViewTj Holowaychukbefore adoptione1da383

lines 568–571why, one step back
568 // set .cache unless explicitly provided
569 opts.cache = null == opts.cache570 ? this.enabled('view cache')571 : opts.cache;

application.jsTj Holowaychukbefore adoptiond0585bd

line 572why, one step back
572

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 575why, one step back
575

new ViewTj Holowaychukbefore adoptione1da383

lines 576–582why, one step back
576 // view
577 if (!view) {578 view = new View(name, {579 defaultEngine: this.set('view engine')580 , root: this.set('views') || process.cwd() + '/views'581 , engines: engines582 });

application.jsTj Holowaychukbefore adoptiond0585bd

line 583why, one step back
583

new ViewTj Holowaychukbefore adoptione1da383

lines 584–587why, one step back
584 // prime the cache
585 if (opts.cache) cache[name] = view;586 }587

application.jsTj Holowaychukbefore adoptiond0585bd

lines 588–589why, one step back
588 // render
589 try {

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 591–594why, one step back
591 } catch (err) {
592 fn(err);593 }594};