application.js
This file
Path
lib/application.js
592 lines · 12.4 KiB · JavaScript
Last changed by
Fixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4
History of this fileTake it
application.jsTj Holowaychukbefore adoptiond0585bd
lines 1–16why, 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 , toArray = require('./utils').toArray15 , methods = Router.methods.concat('del', 'all')16 , res = require('./response')new ViewTj Holowaychukbefore adoptione1da383
line 17why, one step back17 , View = require('./view')application.jsTj Holowaychukbefore adoptiond0585bd
lines 18–33why, one step back18 , 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 back34 * - setup default configuration35 * - setup default middleware36 * - setup route reflection methods37 *application.jsTj Holowaychukbefore adoptiond0585bd
lines 38–40why, one step back38 * @api private39 */40refactoring boot logicTj Holowaychukbefore adoption8848004
line 41why, one step back41app.init = function(){application.jsTj Holowaychukbefore adoptiond0585bd
line 42why, one step back42 var self = this;app.lookup()Tj Holowaychukbefore adoption76b7d69
line 43why, one step back43 this.cache = {};application.jsTj Holowaychukbefore adoptiond0585bd
line 44why, one step back44 this.settings = {};added app.register()Tj Holowaychukbefore adoptiona9396ef
line 45why, one step back45 this.engines = {};application.jsTj Holowaychukbefore adoptiond0585bd
lines 46–47why, one step back46 this.redirects = {};47 this.isCallbacks = {};app.locals.use(fn)Tj Holowaychukbefore adoption0f6ad43
line 48why, one step back48 this.viewCallbacks = [];refactoring boot logicTj Holowaychukbefore adoption8848004
line 49why, one step back49 this.defaultConfiguration();application.jsTj Holowaychukbefore adoptiond0585bd
line 50why, one step back50miscTj Holowaychukbefore adoptiond4b08e9
line 51why, one step back51 // route reflection methodsrefactoring boot logicTj Holowaychukbefore adoption8848004
lines 52–53why, one step back52 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 back54 return self._router.lookup(method, path);refactoring boot logicTj Holowaychukbefore adoption8848004
lines 55–57why, one step back55 };5657 self.match[method] = function(path){Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 58why, one step back58 return self._router.match(method, path);refactoring boot logicTj Holowaychukbefore adoption8848004
lines 59–61why, one step back59 };6061 self.remove[method] = function(path){Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 62why, one step back62 return self._router.lookup(method, path).remove();refactoring boot logicTj Holowaychukbefore adoption8848004
lines 63–80why, one step back63 };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;80req.query is always presentTj Holowaychukbefore adoptiond1ce4c9
line 81why, one step back81 // default settingsFixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4
line 82why, one step back82 this.set('root', '/');application.jsTj Holowaychukbefore adoptiond0585bd
line 83why, one step back83 this.set('env', process.env.NODE_ENV || 'development');req.query is always presentTj Holowaychukbefore adoptiond1ce4c9
lines 84–85why, one step back8485 // always parse req.queryapplication.jsTj Holowaychukbefore adoptiond0585bd
lines 86–88why, one step back86 this.use(connect.query());8788 this.locals = function(obj){misc refactoringTj Holowaychukbefore adoption4ed92d5
line 89why, one step back89 for (var key in obj) self.locals[key] = obj[key];application.jsTj Holowaychukbefore adoptiond0585bd
line 90why, one step back90 return self;app.locals.use(fn)Tj Holowaychukbefore adoption0f6ad43
lines 91–93why, one step back91 };9293 this.locals.use = function(fn){added sync signature for app.locals.use()Tj Holowaychukbefore adoption965e1d6
lines 94–101why, one step back94 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 back102 return this;application.jsTj Holowaychukbefore adoptiond0585bd
lines 103–117why, one step back103 };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 back118 for (var key in obj) res.locals[key] = obj[key];application.jsTj Holowaychukbefore adoptiond0585bd
lines 119–125why, one step back119 return res;120 };121122 next();123 });124125 // routerAdded `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
lines 126–127why, one step back126 this._router = new Router(this);127 this.routes = this._router.routes;application.jsTj Holowaychukbefore adoptiond0585bd
lines 128–129why, one step back128 this.__defineGetter__('router', function(){129 this.__usedRouter = true;Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 130why, one step back130 return self._router.middleware;application.jsTj Holowaychukbefore adoptiond0585bd
lines 131–150why, one step back131 });132133 // default locals134 this.locals.settings = this.settings;135136 // default production configuration137 this.configure('production', function(){138 this.enable('view cache');139 });140};141142/**143 * Remove routes matching the given `path`.144 *145 * @param {Route} path146 * @return {Boolean}147 * @api public148 */149150app.remove = function(path){Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 151why, one step back151 return this._router.lookup('all', path).remove();application.jsTj Holowaychukbefore adoptiond0585bd
lines 152–163why, one step back152};153154/**155 * Lookup routes defined with a path156 * equivalent to `path`.157 *158 * @param {Stirng} path159 * @return {Array}160 * @api public161 */162163app.lookup = function(path){Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 164why, one step back164 return this._router.lookup('all', path);application.jsTj Holowaychukbefore adoptiond0585bd
lines 165–175why, one step back165};166167/**168 * Lookup routes matching the given `url`.169 *170 * @param {Stirng} url171 * @return {Array}172 * @api public173 */174175app.match = function(url){Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 176why, one step back176 return this._router.match('all', url);application.jsTj Holowaychukbefore adoptiond0585bd
lines 177–253why, one step back177};178179/**180 * Proxy `connect.HTTPServer#use()` to apply settings to181 * mounted applications.182 *183 * @param {String|Function|Server} route184 * @param {Function|Server} middleware185 * @return {Server} for chaining186 * @api public187 */188189app.use = function(route, middleware){190 var app, home, handle;191192 if ('string' != typeof route) {193 middleware = route, route = '/';194 }195196 // express app197 if (middleware.handle && middleware.set) app = middleware;198199 // restore .app property on req and res200 if (app) {201 app.route = route;202 middleware = function(req, res, next) {203 var orig = req.app;204 app.handle(req, res, function(err){205 req.app = res.app = orig;206 next(err);207 });208 };209 }210211 connect.proto.use.call(this, route, middleware);212213 // mounted an app, invoke the hook214 // and adjust some settings215 if (app) {216 base = this.set('basepath') || this.route;217 if ('/' == base) base = '';218 base = base + (app.set('basepath') || app.route);219 app.set('basepath', base);220 app.parent = this;221 if (app.__mounted) app.__mounted.call(app, this);222 }223224 return this;225};226227/**228 * Assign a callback `fn` which is called229 * when this `Server` is passed to `Server#use()`.230 *231 * Examples:232 *233 * var app = express.createServer()234 * , blog = express.createServer();235 *236 * blog.mounted(function(parent){237 * // parent is app238 * // "this" is blog239 * });240 *241 * app.use(blog);242 *243 * @param {Function} fn244 * @return {Server} for chaining245 * @api public246 */247248app.mounted = function(fn){249 this.__mounted = fn;250 return this;251};252253/**added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 254–256why, one step back254 * Register the given template engine callback `fn`255 * as `ext`. For example we may wish to map ".html"256 * files to ejs rather than using the ".ejs" extension.application.jsTj Holowaychukbefore adoptiond0585bd
line 257why, one step back257 *added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 258–265why, one step back258 * app.register('.html', require('ejs').render);259 *260 * or261 *262 * app.register('html', require('ejs').render);263 *264 * @param {String} ext265 * @param {Function} fnapplication.jsTj Holowaychukbefore adoptiond0585bd
lines 266–269why, one step back266 * @return {Server} for chaining267 * @api public268 */269added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 270–272why, one step back270app.register = function(ext, fn){271 if ('.' != ext[0]) ext = '.' + ext;272 this.engines[ext] = fn;application.jsTj Holowaychukbefore adoptiond0585bd
lines 273–347why, one step back273 return this;274};275276/**277 * Map the given param placeholder `name`(s) to the given callback(s).278 *279 * Param mapping is used to provide pre-conditions to routes280 * which us normalized placeholders. This callback has the same281 * signature as regular middleware, for example below when ":userId"282 * is used this function will be invoked in an attempt to load the user.283 *284 * app.param('userId', function(req, res, next, id){285 * User.find(id, function(err, user){286 * if (err) {287 * next(err);288 * } else if (user) {289 * req.user = user;290 * next();291 * } else {292 * next(new Error('failed to load user'));293 * }294 * });295 * });296 *297 * Passing a single function allows you to map logic298 * to the values passed to `app.param()`, for example299 * this is useful to provide coercion support in a concise manner.300 *301 * The following example maps regular expressions to param values302 * ensuring that they match, otherwise passing control to the next303 * route:304 *305 * app.param(function(name, regexp){306 * if (regexp instanceof RegExp) {307 * return function(req, res, next, val){308 * var captures;309 * if (captures = regexp.exec(String(val))) {310 * req.params[name] = captures;311 * next();312 * } else {313 * next('route');314 * }315 * }316 * }317 * });318 *319 * We can now use it as shown below, where "/commit/:commit" expects320 * that the value for ":commit" is at 5 or more digits. The capture321 * groups are then available as `req.params.commit` as we defined322 * in the function above.323 *324 * app.param('commit', /^\d{5,}$/);325 *326 * For more of this useful functionality take a look327 * at [express-params](http://github.com/visionmedia/express-params).328 *329 * @param {String|Array|Function} name330 * @param {Function} fn331 * @return {Server} for chaining332 * @api public333 */334335app.param = function(name, fn){336 var self = this337 , fns = [].slice.call(arguments, 1);338339 // array340 if (Array.isArray(name)) {341 name.forEach(function(name){342 fns.forEach(function(fn){343 self.param(name, fn);344 });345 });346 // param logic347 } else if ('function' == typeof name) {Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 348why, one step back348 this._router.param(name);application.jsTj Holowaychukbefore adoptiond0585bd
lines 349–352why, one step back349 // single350 } else {351 if (':' == name[0]) name = name.substr(1);352 fns.forEach(function(fn){Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
line 353why, one step back353 self._router.param(name, fn);application.jsTj Holowaychukbefore adoptiond0585bd
lines 354–500why, one step back354 });355 }356357 return this;358};359360/**361 * Register the given callback `fn` for the given `type`.362 *363 * @param {String} type364 * @param {Function} fn365 * @return {Server} for chaining366 * @api public367 */368369app.is = function(type, fn){370 if (!fn) return this.isCallbacks[type];371 this.isCallbacks[type] = fn;372 return this;373};374375/**376 * Assign `setting` to `val`, or return `setting`'s value.377 * Mounted servers inherit their parent server's settings.378 *379 * @param {String} setting380 * @param {String} val381 * @return {Server|Mixed} for chaining, or the setting value382 * @api public383 */384385app.set = function(setting, val){386 if (val === undefined) {387 if (this.settings.hasOwnProperty(setting)) {388 return this.settings[setting];389 } else if (this.parent) {390 return this.parent.set(setting);391 }392 } else {393 this.settings[setting] = val;394 return this;395 }396};397398/**399 * Check if `setting` is enabled.400 *401 * @param {String} setting402 * @return {Boolean}403 * @api public404 */405406app.enabled = function(setting){407 return !!this.set(setting);408};409410/**411 * Check if `setting` is disabled.412 *413 * @param {String} setting414 * @return {Boolean}415 * @api public416 */417418app.disabled = function(setting){419 return !this.set(setting);420};421422/**423 * Enable `setting`.424 *425 * @param {String} setting426 * @return {Server} for chaining427 * @api public428 */429430app.enable = function(setting){431 return this.set(setting, true);432};433434/**435 * Disable `setting`.436 *437 * @param {String} setting438 * @return {Server} for chaining439 * @api public440 */441442app.disable = function(setting){443 return this.set(setting, false);444};445446/**447 * Redirect `key` to `url`.448 *449 * @param {String} key450 * @param {String} url451 * @return {Server} for chaining452 * @api public453 */454455app.redirect = function(key, url){456 this.redirects[key] = url;457 return this;458};459460/**461 * Configure callback for zero or more envs,462 * when no env is specified that callback will463 * be invoked for all environments. Any combination464 * can be used multiple times, in any order desired.465 *466 * Examples:467 *468 * app.configure(function(){469 * // executed for all envs470 * });471 *472 * app.configure('stage', function(){473 * // executed staging env474 * });475 *476 * app.configure('stage', 'production', function(){477 * // executed for stage and production478 * });479 *480 * @param {String} env...481 * @param {Function} fn482 * @return {Server} for chaining483 * @api public484 */485486app.configure = function(env, fn){487 var envs = 'all'488 , args = toArray(arguments);489 fn = args.pop();490 if (args.length) envs = args;491 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);492 return this;493};494495/**496 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.497 */498499methods.forEach(function(method){500 app[method] = function(path){Added `app.get(setting)`. Closes #842Tj Holowaychukbefore adoptione0bd0d6
line 501why, one step back501 if ('get' == method && 1 == arguments.length) return this.set(path); application.jsTj Holowaychukbefore adoptiond0585bd
line 502why, one step back502 var args = [method].concat(toArray(arguments));Added `app.routes`, replacing `app.routes.all()`. Closes #811Tj Holowaychukbefore adoption62257bc
lines 503–504why, one step back503 if (!this.__usedRouter) this.use(this._router);504 return this._router._route.apply(this._router, args);application.jsTj Holowaychukbefore adoptiond0585bd
lines 505–531why, one step back505 }506});507508/**509 * Special-cased "all" method, applying the given route `path`,510 * middleware, and callback to _every_ HTTP method.511 *512 * @param {String} path513 * @param {Function} ...514 * @return {Server} for chaining515 * @api public516 */517518app.all = function(path){519 var args = arguments;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 back532 * Render the given view `name` name with `options`application.jsTj Holowaychukbefore adoptiond0585bd
lines 533–535why, one step back533 * and a callback accepting an error and the534 * rendered template string.535 *new ViewTj Holowaychukbefore adoptione1da383
line 536why, one step back536 * @param {String} namemisc refactoringTj Holowaychukbefore adoption294bc8c
line 537why, one step back537 * @param {String|Function} options or fnapplication.jsTj Holowaychukbefore adoptiond0585bd
lines 538–541why, one step back538 * @param {Function} fn539 * @api public540 */541new ViewTj Holowaychukbefore adoptione1da383
line 542why, one step back542app.render = function(name, options, fn){application.jsTj Holowaychukbefore adoptiond0585bd
line 543why, one step back543 var self = thismerging res.localsTj Holowaychukbefore adoption98e2c05
line 544why, one step back544 , opts = {}re-implemented "view cache"Tj Holowaychukbefore adoption8a38211
line 545why, one step back545 , cache = this.cachenew ViewTj Holowaychukbefore adoptione1da383
lines 546–547why, one step back546 , engines = this.engines547 , view;application.jsTj Holowaychukbefore adoptiond0585bd
lines 548–549why, one step back548549 // support callback function as second argmisc refactoringTj Holowaychukbefore adoption294bc8c
lines 550–551why, one step back550 if ('function' == typeof options) {551 fn = options, options = {};application.jsTj Holowaychukbefore adoptiond0585bd
lines 552–554why, one step back552 }553554 // merge app.localsmerging res.localsTj Holowaychukbefore adoption98e2c05
line 555why, one step back555 utils.merge(opts, this.locals);application.jsTj Holowaychukbefore adoptiond0585bd
line 556why, one step back556merging res.localsTj Holowaychukbefore adoption98e2c05
lines 557–565why, one step back557 // merge options.locals558 if (options.locals) {559 utils.merge(opts, options.locals);560 delete opts.locals;561 }562563 // merge options564 utils.merge(opts, options);565new ViewTj Holowaychukbefore adoptione1da383
lines 566–569why, one step back566 // set .cache unless explicitly provided567 opts.cache = null == opts.cache568 ? this.enabled('view cache')569 : opts.cache;application.jsTj Holowaychukbefore adoptiond0585bd
line 570why, one step back570new ViewTj Holowaychukbefore adoptione1da383
lines 571–572why, one step back571 // primed cache572 if (opts.cache) view = cache[name];application.jsTj Holowaychukbefore adoptiond0585bd
line 573why, one step back573new ViewTj Holowaychukbefore adoptione1da383
lines 574–580why, one step back574 // view575 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 back581new ViewTj Holowaychukbefore adoptione1da383
lines 582–585why, one step back582 // prime the cache583 if (opts.cache) cache[name] = view;584 }585application.jsTj Holowaychukbefore adoptiond0585bd
lines 586–587why, one step back586 // render587 try {new ViewTj Holowaychukbefore adoptione1da383
line 588why, one step back588 view.render(opts, fn);application.jsTj Holowaychukbefore adoptiond0585bd
lines 589–592why, one step back589 } catch (err) {590 fn(err);591 }592};