application.js
This file
Path
lib/application.js
525 lines · 11.1 KiB · JavaScript
Last changed by
Merge pull request #968 from peters/patch-1TJ Holowaychukbefore adoption4eb8bc0
History of this fileTake it
The walk stopped after 200 commits: lines older than 5b296b5 point at it.
middleware testsTj Holowaychukbefore adoption5b296b5
lines 1–13why, one step back1/*!2 * Express - proto3 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>4 * MIT Licensed5 */67/**8 * Module dependencies.9 */1011var connect = require('connect')12 , Router = require('./router')13 , methods = Router.methods.concat('del', 'all')refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 14why, one step back14 , middleware = require('./middleware')middleware testsTj Holowaychukbefore adoption5b296b5
lines 15–18why, one step back15 , View = require('./view')16 , url = require('url')17 , utils = connect.utils18 , path = require('path')Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 19why, one step back19 , http = require('http')middleware testsTj Holowaychukbefore adoption5b296b5
lines 20–24why, one step back20 , join = path.join21 , fs = require('fs')22 , qs = require('qs');2324/**typoTj Holowaychukbefore adoptionc30c2f8
line 25why, one step back25 * Application prototype.middleware testsTj Holowaychukbefore adoption5b296b5
lines 26–75why, one step back26 */2728var app = exports = module.exports = {};2930/**31 * Initialize the server.32 *33 * - setup default configuration34 * - setup default middleware35 * - setup route reflection methods36 *37 * @api private38 */3940app.init = function(){41 var self = this;42 this.cache = {};43 this.settings = {};44 this.engines = {};45 this.viewCallbacks = [];46 this.defaultConfiguration();4748 // route reflection methods49 methods.forEach(function(method){50 self.lookup[method] = function(path){51 return self._router.lookup(method, path);52 };5354 self.remove[method] = function(path){55 return self._router.lookup(method, path).remove();56 };57 });5859 // del -> delete60 self.lookup.del = self.lookup.delete;61 self.remove.del = self.remove.delete;62};6364/**65 * Initialize application configuration.66 *67 * @api private68 */6970app.defaultConfiguration = function(){71 var self = this;7273 // default settings74 this.set('env', process.env.NODE_ENV || 'development');75refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 76why, one step back76 // implicit middlewaremiddleware testsTj Holowaychukbefore adoption5b296b5
line 77why, one step back77 this.use(connect.query());refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 78why, one step back78 this.use(middleware.init(this));middleware testsTj Holowaychukbefore adoption5b296b5
line 79why, one step back79docsTj Holowaychukbefore adoption6ae32fd
line 80why, one step back80 // app localsmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 81–85why, one step back81 this.locals = function(obj){82 for (var key in obj) self.locals[key] = obj[key];83 return self;84 };85docsTj Holowaychukbefore adoption6ae32fd
line 86why, one step back86 // response localsmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 87–102why, one step back87 this.locals.use = function(fn){88 if (3 == fn.length) {89 self.viewCallbacks.push(fn);90 } else {91 self.viewCallbacks.push(function(req, res, done){92 fn(req, res);93 done();94 });95 }96 return this;97 };9899 // router100 this._router = new Router(this);101 this.routes = this._router.routes;102 this.__defineGetter__('router', function(){fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284
line 103why, one step back103 this._usedRouter = true;Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
lines 104–106why, one step back104 this._router.caseSensitive = this.enabled('case sensitive routing');105 this._router.strict = this.enabled('strict routing');106 return this._router.middleware;middleware testsTj Holowaychukbefore adoption5b296b5
lines 107–133why, one step back107 });108109 // default locals110 this.locals.settings = this.settings;111112 // default production configuration113 this.configure('production', function(){114 this.enable('view cache');115 });116};117118/**119 * Remove routes matching the given `path`.120 *121 * @param {Route} path122 * @return {Boolean}123 * @api public124 */125126app.remove = function(path){127 return this._router.lookup('all', path).remove();128};129130/**131 * Lookup routes defined with a path132 * equivalent to `path`.133 *Merge pull request #968 from peters/patch-1TJ Holowaychukbefore adoption4eb8bc0
line 134why, one step back134 * @param {String} pathmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 135–143why, one step back135 * @return {Array}136 * @api public137 */138139app.lookup = function(path){140 return this._router.lookup('all', path);141};142143/**docsTj Holowaychukbefore adoption2e22887
line 144why, one step back144 * Proxy `connect#use()` to apply settings tomiddleware testsTj Holowaychukbefore adoption5b296b5
lines 145–147why, one step back145 * mounted applications.146 *147 * @param {String|Function|Server} routemisc refactoringTj Holowaychukbefore adoption1334a74
line 148why, one step back148 * @param {Function|Server} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 149why, one step back149 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 150–152why, one step back150 * @api public151 */152misc refactoringTj Holowaychukbefore adoption1334a74
line 153why, one step back153app.use = function(route, fn){middleware testsTj Holowaychukbefore adoption5b296b5
lines 154–155why, one step back154 var app, home, handle;155app.path()Tj Holowaychukbefore adoption17a831e
line 156why, one step back156 // default route to '/'misc refactoringTj Holowaychukbefore adoption1334a74
line 157why, one step back157 if ('string' != typeof route) fn = route, route = '/';middleware testsTj Holowaychukbefore adoption5b296b5
lines 158–159why, one step back158159 // express appmisc refactoringTj Holowaychukbefore adoption1334a74
line 160why, one step back160 if (fn.handle && fn.set) app = fn;middleware testsTj Holowaychukbefore adoption5b296b5
lines 161–164why, one step back161162 // restore .app property on req and res163 if (app) {164 app.route = route;misc refactoringTj Holowaychukbefore adoption1334a74
line 165why, one step back165 fn = function(req, res, next) {middleware testsTj Holowaychukbefore adoption5b296b5
lines 166–173why, one step back166 var orig = req.app;167 app.handle(req, res, function(err){168 req.app = res.app = orig;169 next(err);170 });171 };172 }173misc refactoringTj Holowaychukbefore adoption1334a74
line 174why, one step back174 connect.proto.use.call(this, route, fn);middleware testsTj Holowaychukbefore adoption5b296b5
line 175why, one step back175removed "root" settingTj Holowaychukbefore adoption87b991c
line 176why, one step back176 // mounted an appmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 177–178why, one step back177 if (app) {178 app.parent = this;Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8
line 179why, one step back179 app.emit('mount', this);middleware testsTj Holowaychukbefore adoption5b296b5
lines 180–189why, one step back180 }181182 return this;183};184185/**186 * Register the given template engine callback `fn`187 * as `ext`. For example we may wish to map ".html"188 * files to ejs rather than using the ".ejs" extension.189 *Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 190why, one step back190 * app.engine('.html', require('ejs').render);middleware testsTj Holowaychukbefore adoption5b296b5
lines 191–193why, one step back191 *192 * or193 *Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 194why, one step back194 * app.engine('html', require('ejs').render);middleware testsTj Holowaychukbefore adoption5b296b5
lines 195–197why, one step back195 *196 * @param {String} ext197 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 198why, one step back198 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 199–201why, one step back199 * @api public200 */201Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 202why, one step back202app.engine = function(ext, fn){middleware testsTj Holowaychukbefore adoption5b296b5
lines 203–262why, one step back203 if ('.' != ext[0]) ext = '.' + ext;204 this.engines[ext] = fn;205 return this;206};207208/**209 * Map the given param placeholder `name`(s) to the given callback(s).210 *211 * Param mapping is used to provide pre-conditions to routes212 * which us normalized placeholders. This callback has the same213 * signature as regular middleware, for example below when ":userId"214 * is used this function will be invoked in an attempt to load the user.215 *216 * app.param('userId', function(req, res, next, id){217 * User.find(id, function(err, user){218 * if (err) {219 * next(err);220 * } else if (user) {221 * req.user = user;222 * next();223 * } else {224 * next(new Error('failed to load user'));225 * }226 * });227 * });228 *229 * Passing a single function allows you to map logic230 * to the values passed to `app.param()`, for example231 * this is useful to provide coercion support in a concise manner.232 *233 * The following example maps regular expressions to param values234 * ensuring that they match, otherwise passing control to the next235 * route:236 *237 * app.param(function(name, regexp){238 * if (regexp instanceof RegExp) {239 * return function(req, res, next, val){240 * var captures;241 * if (captures = regexp.exec(String(val))) {242 * req.params[name] = captures;243 * next();244 * } else {245 * next('route');246 * }247 * }248 * }249 * });250 *251 * We can now use it as shown below, where "/commit/:commit" expects252 * that the value for ":commit" is at 5 or more digits. The capture253 * groups are then available as `req.params.commit` as we defined254 * in the function above.255 *256 * app.param('commit', /^\d{5,}$/);257 *258 * For more of this useful functionality take a look259 * at [express-params](http://github.com/visionmedia/express-params).260 *261 * @param {String|Array|Function} name262 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 263why, one step back263 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 264–302why, one step back264 * @api public265 */266267app.param = function(name, fn){268 var self = this269 , fns = [].slice.call(arguments, 1);270271 // array272 if (Array.isArray(name)) {273 name.forEach(function(name){274 fns.forEach(function(fn){275 self.param(name, fn);276 });277 });278 // param logic279 } else if ('function' == typeof name) {280 this._router.param(name);281 // single282 } else {283 if (':' == name[0]) name = name.substr(1);284 fns.forEach(function(fn){285 self._router.param(name, fn);286 });287 }288289 return this;290};291292/**293 * Assign `setting` to `val`, or return `setting`'s value.294 * Mounted servers inherit their parent server's settings.295 *296 * @param {String} setting297 * @param {String} val298 * @return {Server|Mixed} for chaining, or the setting value299 * @api public300 */301302app.set = function(setting, val){Fixed app.set() with undefinedTj Holowaychukbefore adoption7d24c2b
line 303why, one step back303 if (1 == arguments.length) {middleware testsTj Holowaychukbefore adoption5b296b5
lines 304–312why, one step back304 if (this.settings.hasOwnProperty(setting)) {305 return this.settings[setting];306 } else if (this.parent) {307 return this.parent.set(setting);308 }309 } else {310 this.settings[setting] = val;311 return this;312 }app.path()Tj Holowaychukbefore adoption17a831e
lines 313–327why, one step back313};314315/**316 * Return the app's absolute pathname317 * based on the parent(s) that have318 * mounted it.319 *320 * @return {String}321 * @api private322 */323324app.path = function(){325 return this.parent326 ? this.parent.path() + this.route327 : '';middleware testsTj Holowaychukbefore adoption5b296b5
lines 328–357why, one step back328};329330/**331 * Check if `setting` is enabled.332 *333 * @param {String} setting334 * @return {Boolean}335 * @api public336 */337338app.enabled = function(setting){339 return !!this.set(setting);340};341342/**343 * Check if `setting` is disabled.344 *345 * @param {String} setting346 * @return {Boolean}347 * @api public348 */349350app.disabled = function(setting){351 return !this.set(setting);352};353354/**355 * Enable `setting`.356 *357 * @param {String} settingAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 358why, one step back358 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 359–369why, one step back359 * @api public360 */361362app.enable = function(setting){363 return this.set(setting, true);364};365366/**367 * Disable `setting`.368 *369 * @param {String} settingAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 370why, one step back370 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 371–399why, one step back371 * @api public372 */373374app.disable = function(setting){375 return this.set(setting, false);376};377378/**379 * Configure callback for zero or more envs,380 * when no env is specified that callback will381 * be invoked for all environments. Any combination382 * can be used multiple times, in any order desired.383 *384 * Examples:385 *386 * app.configure(function(){387 * // executed for all envs388 * });389 *390 * app.configure('stage', function(){391 * // executed staging env392 * });393 *394 * app.configure('stage', 'production', function(){395 * // executed for stage and production396 * });397 *398 * @param {String} env...399 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 400why, one step back400 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 401–405why, one step back401 * @api public402 */403404app.configure = function(env, fn){405 var envs = 'all'Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
line 406why, one step back406 , args = [].slice.call(arguments);middleware testsTj Holowaychukbefore adoption5b296b5
lines 407–413why, one step back407 fn = args.pop();408 if (args.length) envs = args;409 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);410 return this;411};412413/**Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
lines 414–428why, one step back414 * Listen for connections.415 *416 * This method takes the same arguments417 * as node's `http.Server#listen()`. 418 *419 * @return {http.Server}420 * @api public421 */422423app.listen = function(){424 var server = http.createServer(this);425 return server.listen.apply(server, arguments);426};427428/**middleware testsTj Holowaychukbefore adoption5b296b5
lines 429–434why, one step back429 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.430 */431432methods.forEach(function(method){433 app[method] = function(path){434 if ('get' == method && 1 == arguments.length) return this.set(path); Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
line 435why, one step back435 var args = [method].concat([].slice.call(arguments));fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284
line 436why, one step back436 if (!this._usedRouter) this.use(this.router);Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
line 437why, one step back437 return this._router.route.apply(this._router, args);middleware testsTj Holowaychukbefore adoption5b296b5
lines 438–446why, one step back438 }439});440441/**442 * Special-cased "all" method, applying the given route `path`,443 * middleware, and callback to _every_ HTTP method.444 *445 * @param {String} path446 * @param {Function} ...Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 447why, one step back447 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 448–509why, one step back448 * @api public449 */450451app.all = function(path){452 var args = arguments;453 methods.forEach(function(method){454 if ('all' == method) return;455 app[method].apply(this, args);456 }, this);457 return this;458};459460// del -> delete alias461462app.del = app.delete;463464/**465 * Render the given view `name` name with `options`466 * and a callback accepting an error and the467 * rendered template string.468 *469 * @param {String} name470 * @param {String|Function} options or fn471 * @param {Function} fn472 * @api public473 */474475app.render = function(name, options, fn){476 var self = this477 , opts = {}478 , cache = this.cache479 , engines = this.engines480 , view;481482 // support callback function as second arg483 if ('function' == typeof options) {484 fn = options, options = {};485 }486487 // merge app.locals488 utils.merge(opts, this.locals);489490 // merge options.locals491 if (options.locals) {492 utils.merge(opts, options.locals);493 delete opts.locals;494 }495496 // merge options497 utils.merge(opts, options);498499 // set .cache unless explicitly provided500 opts.cache = null == opts.cache501 ? this.enabled('view cache')502 : opts.cache;503504 // primed cache505 if (opts.cache) view = cache[name];506507 // view508 if (!view) {509 view = new View(name, {Fixed app.render() absolute path supportTj Holowaychukbefore adoptionb9dee73
lines 510–511why, one step back510 defaultEngine: this.get('view engine')511 , root: this.get('views') || process.cwd() + '/views'middleware testsTj Holowaychukbefore adoption5b296b5
lines 512–525why, one step back512 , engines: engines513 });514515 // prime the cache516 if (opts.cache) cache[name] = view;517 }518519 // render520 try {521 view.render(opts, fn);522 } catch (err) {523 fn(err);524 }525};