application.js
This file
Path
lib/application.js
526 lines · 11.1 KiB · JavaScript
Last changed by
Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
History of this fileTake it
The walk stopped after 200 commits: lines older than 5b296b5 point at it.
middleware testsTj Holowaychukbefore adoption5b296b5
lines 1–14why, one step back12/*!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 , methods = Router.methods.concat('del', 'all')refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 15why, one step back15 , middleware = require('./middleware')middleware testsTj Holowaychukbefore adoption5b296b5
lines 16–19why, one step back16 , View = require('./view')17 , url = require('url')18 , utils = connect.utils19 , path = require('path')Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 20why, one step back20 , http = require('http')middleware testsTj Holowaychukbefore adoption5b296b5
lines 21–25why, one step back21 , join = path.join22 , fs = require('fs')23 , qs = require('qs');2425/**typoTj Holowaychukbefore adoptionc30c2f8
line 26why, one step back26 * Application prototype.middleware testsTj Holowaychukbefore adoption5b296b5
lines 27–76why, one step back27 */2829var app = exports = module.exports = {};3031/**32 * Initialize the server.33 *34 * - setup default configuration35 * - setup default middleware36 * - setup route reflection methods37 *38 * @api private39 */4041app.init = function(){42 var self = this;43 this.cache = {};44 this.settings = {};45 this.engines = {};46 this.viewCallbacks = [];47 this.defaultConfiguration();4849 // route reflection methods50 methods.forEach(function(method){51 self.lookup[method] = function(path){52 return self._router.lookup(method, path);53 };5455 self.remove[method] = function(path){56 return self._router.lookup(method, path).remove();57 };58 });5960 // del -> delete61 self.lookup.del = self.lookup.delete;62 self.remove.del = self.remove.delete;63};6465/**66 * Initialize application configuration.67 *68 * @api private69 */7071app.defaultConfiguration = function(){72 var self = this;7374 // default settings75 this.set('env', process.env.NODE_ENV || 'development');76refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 77why, one step back77 // implicit middlewaremiddleware testsTj Holowaychukbefore adoption5b296b5
line 78why, one step back78 this.use(connect.query());refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 79why, one step back79 this.use(middleware.init(this));middleware testsTj Holowaychukbefore adoption5b296b5
line 80why, one step back80docsTj Holowaychukbefore adoption6ae32fd
line 81why, one step back81 // app localsmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 82–86why, one step back82 this.locals = function(obj){83 for (var key in obj) self.locals[key] = obj[key];84 return self;85 };86docsTj Holowaychukbefore adoption6ae32fd
line 87why, one step back87 // response localsmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 88–103why, one step back88 this.locals.use = function(fn){89 if (3 == fn.length) {90 self.viewCallbacks.push(fn);91 } else {92 self.viewCallbacks.push(function(req, res, done){93 fn(req, res);94 done();95 });96 }97 return this;98 };99100 // router101 this._router = new Router(this);102 this.routes = this._router.routes;103 this.__defineGetter__('router', function(){fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284
line 104why, one step back104 this._usedRouter = true;Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
lines 105–107why, one step back105 this._router.caseSensitive = this.enabled('case sensitive routing');106 this._router.strict = this.enabled('strict routing');107 return this._router.middleware;middleware testsTj Holowaychukbefore adoption5b296b5
lines 108–144why, one step back108 });109110 // default locals111 this.locals.settings = this.settings;112113 // default production configuration114 this.configure('production', function(){115 this.enable('view cache');116 });117};118119/**120 * Remove routes matching the given `path`.121 *122 * @param {Route} path123 * @return {Boolean}124 * @api public125 */126127app.remove = function(path){128 return this._router.lookup('all', path).remove();129};130131/**132 * Lookup routes defined with a path133 * equivalent to `path`.134 *135 * @param {Stirng} path136 * @return {Array}137 * @api public138 */139140app.lookup = function(path){141 return this._router.lookup('all', path);142};143144/**docsTj Holowaychukbefore adoption2e22887
line 145why, one step back145 * Proxy `connect#use()` to apply settings tomiddleware testsTj Holowaychukbefore adoption5b296b5
lines 146–148why, one step back146 * mounted applications.147 *148 * @param {String|Function|Server} routemisc refactoringTj Holowaychukbefore adoption1334a74
line 149why, one step back149 * @param {Function|Server} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 150why, one step back150 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 151–153why, one step back151 * @api public152 */153misc refactoringTj Holowaychukbefore adoption1334a74
line 154why, one step back154app.use = function(route, fn){middleware testsTj Holowaychukbefore adoption5b296b5
lines 155–156why, one step back155 var app, home, handle;156app.path()Tj Holowaychukbefore adoption17a831e
line 157why, one step back157 // default route to '/'misc refactoringTj Holowaychukbefore adoption1334a74
line 158why, one step back158 if ('string' != typeof route) fn = route, route = '/';middleware testsTj Holowaychukbefore adoption5b296b5
lines 159–160why, one step back159160 // express appmisc refactoringTj Holowaychukbefore adoption1334a74
line 161why, one step back161 if (fn.handle && fn.set) app = fn;middleware testsTj Holowaychukbefore adoption5b296b5
lines 162–165why, one step back162163 // restore .app property on req and res164 if (app) {165 app.route = route;misc refactoringTj Holowaychukbefore adoption1334a74
line 166why, one step back166 fn = function(req, res, next) {middleware testsTj Holowaychukbefore adoption5b296b5
lines 167–174why, one step back167 var orig = req.app;168 app.handle(req, res, function(err){169 req.app = res.app = orig;170 next(err);171 });172 };173 }174misc refactoringTj Holowaychukbefore adoption1334a74
line 175why, one step back175 connect.proto.use.call(this, route, fn);middleware testsTj Holowaychukbefore adoption5b296b5
line 176why, one step back176removed "root" settingTj Holowaychukbefore adoption87b991c
line 177why, one step back177 // mounted an appmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 178–179why, one step back178 if (app) {179 app.parent = this;Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8
line 180why, one step back180 app.emit('mount', this);middleware testsTj Holowaychukbefore adoption5b296b5
lines 181–190why, one step back181 }182183 return this;184};185186/**187 * Register the given template engine callback `fn`188 * as `ext`. For example we may wish to map ".html"189 * files to ejs rather than using the ".ejs" extension.190 *Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 191why, one step back191 * app.engine('.html', require('ejs').render);middleware testsTj Holowaychukbefore adoption5b296b5
lines 192–194why, one step back192 *193 * or194 *Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 195why, one step back195 * app.engine('html', require('ejs').render);middleware testsTj Holowaychukbefore adoption5b296b5
lines 196–198why, one step back196 *197 * @param {String} ext198 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 199why, one step back199 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 200–202why, one step back200 * @api public201 */202Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 203why, one step back203app.engine = function(ext, fn){middleware testsTj Holowaychukbefore adoption5b296b5
lines 204–263why, one step back204 if ('.' != ext[0]) ext = '.' + ext;205 this.engines[ext] = fn;206 return this;207};208209/**210 * Map the given param placeholder `name`(s) to the given callback(s).211 *212 * Param mapping is used to provide pre-conditions to routes213 * which us normalized placeholders. This callback has the same214 * signature as regular middleware, for example below when ":userId"215 * is used this function will be invoked in an attempt to load the user.216 *217 * app.param('userId', function(req, res, next, id){218 * User.find(id, function(err, user){219 * if (err) {220 * next(err);221 * } else if (user) {222 * req.user = user;223 * next();224 * } else {225 * next(new Error('failed to load user'));226 * }227 * });228 * });229 *230 * Passing a single function allows you to map logic231 * to the values passed to `app.param()`, for example232 * this is useful to provide coercion support in a concise manner.233 *234 * The following example maps regular expressions to param values235 * ensuring that they match, otherwise passing control to the next236 * route:237 *238 * app.param(function(name, regexp){239 * if (regexp instanceof RegExp) {240 * return function(req, res, next, val){241 * var captures;242 * if (captures = regexp.exec(String(val))) {243 * req.params[name] = captures;244 * next();245 * } else {246 * next('route');247 * }248 * }249 * }250 * });251 *252 * We can now use it as shown below, where "/commit/:commit" expects253 * that the value for ":commit" is at 5 or more digits. The capture254 * groups are then available as `req.params.commit` as we defined255 * in the function above.256 *257 * app.param('commit', /^\d{5,}$/);258 *259 * For more of this useful functionality take a look260 * at [express-params](http://github.com/visionmedia/express-params).261 *262 * @param {String|Array|Function} name263 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 264why, one step back264 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 265–303why, one step back265 * @api public266 */267268app.param = function(name, fn){269 var self = this270 , fns = [].slice.call(arguments, 1);271272 // array273 if (Array.isArray(name)) {274 name.forEach(function(name){275 fns.forEach(function(fn){276 self.param(name, fn);277 });278 });279 // param logic280 } else if ('function' == typeof name) {281 this._router.param(name);282 // single283 } else {284 if (':' == name[0]) name = name.substr(1);285 fns.forEach(function(fn){286 self._router.param(name, fn);287 });288 }289290 return this;291};292293/**294 * Assign `setting` to `val`, or return `setting`'s value.295 * Mounted servers inherit their parent server's settings.296 *297 * @param {String} setting298 * @param {String} val299 * @return {Server|Mixed} for chaining, or the setting value300 * @api public301 */302303app.set = function(setting, val){Fixed app.set() with undefinedTj Holowaychukbefore adoption7d24c2b
line 304why, one step back304 if (1 == arguments.length) {middleware testsTj Holowaychukbefore adoption5b296b5
lines 305–313why, one step back305 if (this.settings.hasOwnProperty(setting)) {306 return this.settings[setting];307 } else if (this.parent) {308 return this.parent.set(setting);309 }310 } else {311 this.settings[setting] = val;312 return this;313 }app.path()Tj Holowaychukbefore adoption17a831e
lines 314–328why, one step back314};315316/**317 * Return the app's absolute pathname318 * based on the parent(s) that have319 * mounted it.320 *321 * @return {String}322 * @api private323 */324325app.path = function(){326 return this.parent327 ? this.parent.path() + this.route328 : '';middleware testsTj Holowaychukbefore adoption5b296b5
lines 329–358why, one step back329};330331/**332 * Check if `setting` is enabled.333 *334 * @param {String} setting335 * @return {Boolean}336 * @api public337 */338339app.enabled = function(setting){340 return !!this.set(setting);341};342343/**344 * Check if `setting` is disabled.345 *346 * @param {String} setting347 * @return {Boolean}348 * @api public349 */350351app.disabled = function(setting){352 return !this.set(setting);353};354355/**356 * Enable `setting`.357 *358 * @param {String} settingAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 359why, one step back359 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 360–370why, one step back360 * @api public361 */362363app.enable = function(setting){364 return this.set(setting, true);365};366367/**368 * Disable `setting`.369 *370 * @param {String} settingAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 371why, one step back371 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 372–400why, one step back372 * @api public373 */374375app.disable = function(setting){376 return this.set(setting, false);377};378379/**380 * Configure callback for zero or more envs,381 * when no env is specified that callback will382 * be invoked for all environments. Any combination383 * can be used multiple times, in any order desired.384 *385 * Examples:386 *387 * app.configure(function(){388 * // executed for all envs389 * });390 *391 * app.configure('stage', function(){392 * // executed staging env393 * });394 *395 * app.configure('stage', 'production', function(){396 * // executed for stage and production397 * });398 *399 * @param {String} env...400 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 401why, one step back401 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 402–406why, one step back402 * @api public403 */404405app.configure = function(env, fn){406 var envs = 'all'Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
line 407why, one step back407 , args = [].slice.call(arguments);middleware testsTj Holowaychukbefore adoption5b296b5
lines 408–414why, one step back408 fn = args.pop();409 if (args.length) envs = args;410 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);411 return this;412};413414/**Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
lines 415–429why, one step back415 * Listen for connections.416 *417 * This method takes the same arguments418 * as node's `http.Server#listen()`. 419 *420 * @return {http.Server}421 * @api public422 */423424app.listen = function(){425 var server = http.createServer(this);426 return server.listen.apply(server, arguments);427};428429/**middleware testsTj Holowaychukbefore adoption5b296b5
lines 430–435why, one step back430 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.431 */432433methods.forEach(function(method){434 app[method] = function(path){435 if ('get' == method && 1 == arguments.length) return this.set(path); Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
line 436why, one step back436 var args = [method].concat([].slice.call(arguments));fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284
line 437why, one step back437 if (!this._usedRouter) this.use(this.router);Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
line 438why, one step back438 return this._router.route.apply(this._router, args);middleware testsTj Holowaychukbefore adoption5b296b5
lines 439–447why, one step back439 }440});441442/**443 * Special-cased "all" method, applying the given route `path`,444 * middleware, and callback to _every_ HTTP method.445 *446 * @param {String} path447 * @param {Function} ...Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 448why, one step back448 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 449–510why, one step back449 * @api public450 */451452app.all = function(path){453 var args = arguments;454 methods.forEach(function(method){455 if ('all' == method) return;456 app[method].apply(this, args);457 }, this);458 return this;459};460461// del -> delete alias462463app.del = app.delete;464465/**466 * Render the given view `name` name with `options`467 * and a callback accepting an error and the468 * rendered template string.469 *470 * @param {String} name471 * @param {String|Function} options or fn472 * @param {Function} fn473 * @api public474 */475476app.render = function(name, options, fn){477 var self = this478 , opts = {}479 , cache = this.cache480 , engines = this.engines481 , view;482483 // support callback function as second arg484 if ('function' == typeof options) {485 fn = options, options = {};486 }487488 // merge app.locals489 utils.merge(opts, this.locals);490491 // merge options.locals492 if (options.locals) {493 utils.merge(opts, options.locals);494 delete opts.locals;495 }496497 // merge options498 utils.merge(opts, options);499500 // set .cache unless explicitly provided501 opts.cache = null == opts.cache502 ? this.enabled('view cache')503 : opts.cache;504505 // primed cache506 if (opts.cache) view = cache[name];507508 // view509 if (!view) {510 view = new View(name, {Fixed app.render() absolute path supportTj Holowaychukbefore adoptionb9dee73
lines 511–512why, one step back511 defaultEngine: this.get('view engine')512 , root: this.get('views') || process.cwd() + '/views'middleware testsTj Holowaychukbefore adoption5b296b5
lines 513–526why, one step back513 , engines: engines514 });515516 // prime the cache517 if (opts.cache) cache[name] = view;518 }519520 // render521 try {522 view.render(opts, fn);523 } catch (err) {524 fn(err);525 }526};