Skip to content
Myr

application.js

This file

Path

lib/application.js

592 lines · 12.4 KiB · JavaScript

Last changed by

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

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–80why, one step back
52 methods.forEach(function(method){
53 self.lookup[method] = function(path){54 return self.routes.lookup(method, path);55 };5657 self.match[method] = function(path){58 return self.routes.match(method, path);59 };6061 self.remove[method] = function(path){62 return self.routes.lookup(method, path).remove();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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 82–83why, one step back
82 this.set('home', '/');
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–117why, 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 // charset115 if (charset = self.set('charset')) res.charset = charset;116117 res.locals = function(obj){

misc refactoringTj Holowaychukbefore adoption4ed92d5

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 119–252why, one step back
119 return res;
120 };121122 next();123 });124125 // router126 this.routes = new Router(this);127 this.__defineGetter__('router', function(){128 this.__usedRouter = true;129 return self.routes.middleware;130 });131132 // default locals133 this.locals.settings = this.settings;134135 // default production configuration136 this.configure('production', function(){137 this.enable('view cache');138 });139};140141/**142 * Remove routes matching the given `path`.143 *144 * @param {Route} path145 * @return {Boolean}146 * @api public147 */148149app.remove = function(path){150 return this.routes.lookup('all', path).remove();151};152153/**154 * Lookup routes defined with a path155 * equivalent to `path`.156 *157 * @param {Stirng} path158 * @return {Array}159 * @api public160 */161162app.lookup = function(path){163 return this.routes.lookup('all', path);164};165166/**167 * Lookup routes matching the given `url`.168 *169 * @param {Stirng} url170 * @return {Array}171 * @api public172 */173174app.match = function(url){175 return this.routes.match('all', url);176};177178/**179 * Proxy `connect.HTTPServer#use()` to apply settings to180 * mounted applications.181 *182 * @param {String|Function|Server} route183 * @param {Function|Server} middleware184 * @return {Server} for chaining185 * @api public186 */187188app.use = function(route, middleware){189 var app, home, handle;190191 if ('string' != typeof route) {192 middleware = route, route = '/';193 }194195 // express app196 if (middleware.handle && middleware.set) app = middleware;197198 // restore .app property on req and res199 if (app) {200 app.route = route;201 middleware = function(req, res, next) {202 var orig = req.app;203 app.handle(req, res, function(err){204 req.app = res.app = orig;205 next(err);206 });207 };208 }209210 connect.proto.use.call(this, route, middleware);211212 // mounted an app, invoke the hook213 // and adjust some settings214 if (app) {215 base = this.set('basepath') || this.route;216 if ('/' == base) base = '';217 base = base + (app.set('basepath') || app.route);218 app.set('basepath', base);219 app.parent = this;220 if (app.__mounted) app.__mounted.call(app, this);221 }222223 return this;224};225226/**227 * Assign a callback `fn` which is called228 * when this `Server` is passed to `Server#use()`.229 *230 * Examples:231 *232 * var app = express.createServer()233 * , blog = express.createServer();234 *235 * blog.mounted(function(parent){236 * // parent is app237 * // "this" is blog238 * });239 *240 * app.use(blog);241 *242 * @param {Function} fn243 * @return {Server} for chaining244 * @api public245 */246247app.mounted = function(fn){248 this.__mounted = fn;249 return this;250};251252/**

added app.register()Tj Holowaychukbefore adoptiona9396ef

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 256why, one step back
256 *

added app.register()Tj Holowaychukbefore adoptiona9396ef

lines 257–264why, one step back
257 * app.register('.html', require('ejs').render);
258 *259 * or260 *261 * app.register('html', require('ejs').render);262 *263 * @param {String} ext264 * @param {Function} fn

application.jsTj Holowaychukbefore adoptiond0585bd

lines 265–268why, one step back
265 * @return {Server} for chaining
266 * @api public267 */268

added app.register()Tj Holowaychukbefore adoptiona9396ef

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 272–531why, one step back
272 return this;
273};274275/**276 * Map the given param placeholder `name`(s) to the given callback(s).277 *278 * Param mapping is used to provide pre-conditions to routes279 * which us normalized placeholders. This callback has the same280 * signature as regular middleware, for example below when ":userId"281 * is used this function will be invoked in an attempt to load the user.282 *283 * app.param('userId', function(req, res, next, id){284 * User.find(id, function(err, user){285 * if (err) {286 * next(err);287 * } else if (user) {288 * req.user = user;289 * next();290 * } else {291 * next(new Error('failed to load user'));292 * }293 * });294 * });295 *296 * Passing a single function allows you to map logic297 * to the values passed to `app.param()`, for example298 * this is useful to provide coercion support in a concise manner.299 *300 * The following example maps regular expressions to param values301 * ensuring that they match, otherwise passing control to the next302 * route:303 *304 * app.param(function(name, regexp){305 * if (regexp instanceof RegExp) {306 * return function(req, res, next, val){307 * var captures;308 * if (captures = regexp.exec(String(val))) {309 * req.params[name] = captures;310 * next();311 * } else {312 * next('route');313 * }314 * }315 * }316 * });317 *318 * We can now use it as shown below, where "/commit/:commit" expects319 * that the value for ":commit" is at 5 or more digits. The capture320 * groups are then available as `req.params.commit` as we defined321 * in the function above.322 *323 * app.param('commit', /^\d{5,}$/);324 *325 * For more of this useful functionality take a look326 * at [express-params](http://github.com/visionmedia/express-params).327 *328 * @param {String|Array|Function} name329 * @param {Function} fn330 * @return {Server} for chaining331 * @api public332 */333334app.param = function(name, fn){335 var self = this336 , fns = [].slice.call(arguments, 1);337338 // array339 if (Array.isArray(name)) {340 name.forEach(function(name){341 fns.forEach(function(fn){342 self.param(name, fn);343 });344 });345 // param logic346 } else if ('function' == typeof name) {347 this.routes.param(name);348 // single349 } else {350 if (':' == name[0]) name = name.substr(1);351 fns.forEach(function(fn){352 self.routes.param(name, fn);353 });354 }355356 return this;357};358359/**360 * Register the given callback `fn` for the given `type`.361 *362 * @param {String} type363 * @param {Function} fn364 * @return {Server} for chaining365 * @api public366 */367368app.is = function(type, fn){369 if (!fn) return this.isCallbacks[type];370 this.isCallbacks[type] = fn;371 return this;372};373374/**375 * Assign `setting` to `val`, or return `setting`'s value.376 * Mounted servers inherit their parent server's settings.377 *378 * @param {String} setting379 * @param {String} val380 * @return {Server|Mixed} for chaining, or the setting value381 * @api public382 */383384app.set = function(setting, val){385 if (val === undefined) {386 if (this.settings.hasOwnProperty(setting)) {387 return this.settings[setting];388 } else if (this.parent) {389 return this.parent.set(setting);390 }391 } else {392 this.settings[setting] = val;393 return this;394 }395};396397/**398 * Check if `setting` is enabled.399 *400 * @param {String} setting401 * @return {Boolean}402 * @api public403 */404405app.enabled = function(setting){406 return !!this.set(setting);407};408409/**410 * Check if `setting` is disabled.411 *412 * @param {String} setting413 * @return {Boolean}414 * @api public415 */416417app.disabled = function(setting){418 return !this.set(setting);419};420421/**422 * Enable `setting`.423 *424 * @param {String} setting425 * @return {Server} for chaining426 * @api public427 */428429app.enable = function(setting){430 return this.set(setting, true);431};432433/**434 * Disable `setting`.435 *436 * @param {String} setting437 * @return {Server} for chaining438 * @api public439 */440441app.disable = function(setting){442 return this.set(setting, false);443};444445/**446 * Redirect `key` to `url`.447 *448 * @param {String} key449 * @param {String} url450 * @return {Server} for chaining451 * @api public452 */453454app.redirect = function(key, url){455 this.redirects[key] = url;456 return this;457};458459/**460 * Configure callback for zero or more envs,461 * when no env is specified that callback will462 * be invoked for all environments. Any combination463 * can be used multiple times, in any order desired.464 *465 * Examples:466 *467 * app.configure(function(){468 * // executed for all envs469 * });470 *471 * app.configure('stage', function(){472 * // executed staging env473 * });474 *475 * app.configure('stage', 'production', function(){476 * // executed for stage and production477 * });478 *479 * @param {String} env...480 * @param {Function} fn481 * @return {Server} for chaining482 * @api public483 */484485app.configure = function(env, fn){486 var envs = 'all'487 , args = toArray(arguments);488 fn = args.pop();489 if (args.length) envs = args;490 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);491 return this;492};493494/**495 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.496 */497498methods.forEach(function(method){499 app[method] = function(path){500 if (1 == arguments.length) return this.routes.lookup(method, path);501 var args = [method].concat(toArray(arguments));502 if (!this.__usedRouter) this.use(this.router);503 return this.routes._route.apply(this.routes, args);504 }505});506507/**508 * Special-cased "all" method, applying the given route `path`,509 * middleware, and callback to _every_ HTTP method.510 *511 * @param {String} path512 * @param {Function} ...513 * @return {Server} for chaining514 * @api public515 */516517app.all = function(path){518 var args = arguments;519 if (1 == args.length) return this.routes.lookup('all', path);520 methods.forEach(function(method){521 if ('all' == method) return;522 app[method].apply(this, args);523 }, this);524 return this;525};526527// del -> delete alias528529app.del = app.delete;530531/**

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

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

new ViewTj Holowaychukbefore adoptione1da383

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

misc refactoringTj Holowaychukbefore adoption294bc8c

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 538–541why, one step back
538 * @param {Function} fn
539 * @api public540 */541

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

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

merging res.localsTj Holowaychukbefore adoption98e2c05

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

new ViewTj Holowaychukbefore adoptione1da383

lines 546–547why, one step back
546 , engines = this.engines
547 , view;

application.jsTj Holowaychukbefore adoptiond0585bd

lines 548–549why, one step back
548
549 // support callback function as second arg

misc refactoringTj Holowaychukbefore adoption294bc8c

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 552–554why, one step back
552 }
553554 // merge app.locals

merging res.localsTj Holowaychukbefore adoption98e2c05

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 556why, one step back
556

merging res.localsTj Holowaychukbefore adoption98e2c05

lines 557–565why, one step back
557 // merge options.locals
558 if (options.locals) {559 utils.merge(opts, options.locals);560 delete opts.locals;561 }562563 // merge options564 utils.merge(opts, options);565

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 570why, one step back
570

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 573why, one step back
573

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

line 581why, one step back
581

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

lines 586–587why, one step back
586 // render
587 try {

new ViewTj Holowaychukbefore adoptione1da383

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

application.jsTj Holowaychukbefore adoptiond0585bd

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