application.js
This file
Path
lib/application.js
599 lines · 12.9 KiB · JavaScript
Last changed by
removed union utilTj Holowaychukbefore adoption0d0125f
History of this fileTake it
application.jsTj Holowaychukbefore adoptiond0585bd
lines 1–40why, 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')17 , url = require('url')18 , utils = connect.utils19 , path = require('path')20 , extname = path.extname21 , 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 *34 * @param {Array} middleware35 * @api private36 */3738app.init = function(middleware){39 var self = this;40 this.settings = {};added app.register()Tj Holowaychukbefore adoptiona9396ef
line 41why, one step back41 this.engines = {};application.jsTj Holowaychukbefore adoptiond0585bd
lines 42–252why, one step back42 this.redirects = {};43 this.isCallbacks = {};4445 this.set('home', '/');46 this.set('env', process.env.NODE_ENV || 'development');47 this.use(connect.query());4849 /**50 * Assign several locals with the given `obj`,51 * or return the locals.52 *53 * @param {Object} obj54 * @return {Object|HTTPServer}55 * @api public56 */5758 this.locals = function(obj){59 for (var key in obj) {60 self.locals[key] = obj[key];61 }62 return self;63 };6465 // expose objects to each other66 this.use(function(req, res, next){67 var charset;68 req.query = req.query || {};69 res.setHeader('X-Powered-By', 'Express');70 req.app = res.app = self;71 req.res = res;72 res.req = req;73 req.next = next;7475 // charset76 if (charset = self.set('charset')) res.charset = charset;7778 /**79 * Assign several locals with the given `obj`,80 * or return the locals.81 *82 * @param {Object} obj83 * @return {Object|ServerResponse}84 * @api public85 */8687 res.locals = function(obj){88 for (var key in obj) {89 res.locals[key] = obj[key];90 }91 return res;92 };9394 next();95 });9697 // apply middleware98 if (middleware) middleware.forEach(self.use.bind(self));99100 // router101 this.routes = new Router(this);102 this.__defineGetter__('router', function(){103 this.__usedRouter = true;104 return self.routes.middleware;105 });106107 // default locals108 this.locals.settings = this.settings;109110 // default development configuration111 this.configure('development', function(){112 this.enable('hints');113 });114115 // default production configuration116 this.configure('production', function(){117 this.enable('view cache');118 });119120 // route manipulation methods121 methods.forEach(function(method){122 self.lookup[method] = function(path){123 return self.routes.lookup(method, path);124 };125126 self.match[method] = function(path){127 return self.routes.match(method, path);128 };129130 self.remove[method] = function(path){131 return self.routes.lookup(method, path).remove();132 };133 });134135 // del -> delete136 self.lookup.del = self.lookup.delete;137 self.match.del = self.match.delete;138 self.remove.del = self.remove.delete;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 back253 * 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 back256 *added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 257–264why, one step back257 * app.register('.html', require('ejs').render);258 *259 * or260 *261 * app.register('html', require('ejs').render);262 *263 * @param {String} ext264 * @param {Function} fnapplication.jsTj Holowaychukbefore adoptiond0585bd
lines 265–268why, one step back265 * @return {Server} for chaining266 * @api public267 */268added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 269–271why, one step back269app.register = function(ext, fn){270 if ('.' != ext[0]) ext = '.' + ext;271 this.engines[ext] = fn;application.jsTj Holowaychukbefore adoptiond0585bd
lines 272–546why, one step back272 return this;273};274275/**276 * Map the given param placeholder `name`(s) to the given callback `fn`.277 * Register the given view helpers `obj`. This method278 * can be called several times to apply additional helpers.279 *280 * @param {Object} obj281 * @return {Server} for chaining282 * @api public283 */284285app.locals = function(obj){286 utils.merge(this._locals, obj);287 return this;288};289290/**291 * Map the given param placeholder `name`(s) to the given callback(s).292 *293 * Param mapping is used to provide pre-conditions to routes294 * which us normalized placeholders. This callback has the same295 * signature as regular middleware, for example below when ":userId"296 * is used this function will be invoked in an attempt to load the user.297 *298 * app.param('userId', function(req, res, next, id){299 * User.find(id, function(err, user){300 * if (err) {301 * next(err);302 * } else if (user) {303 * req.user = user;304 * next();305 * } else {306 * next(new Error('failed to load user'));307 * }308 * });309 * });310 *311 * Passing a single function allows you to map logic312 * to the values passed to `app.param()`, for example313 * this is useful to provide coercion support in a concise manner.314 *315 * The following example maps regular expressions to param values316 * ensuring that they match, otherwise passing control to the next317 * route:318 *319 * app.param(function(name, regexp){320 * if (regexp instanceof RegExp) {321 * return function(req, res, next, val){322 * var captures;323 * if (captures = regexp.exec(String(val))) {324 * req.params[name] = captures;325 * next();326 * } else {327 * next('route');328 * }329 * }330 * }331 * });332 *333 * We can now use it as shown below, where "/commit/:commit" expects334 * that the value for ":commit" is at 5 or more digits. The capture335 * groups are then available as `req.params.commit` as we defined336 * in the function above.337 *338 * app.param('commit', /^\d{5,}$/);339 *340 * For more of this useful functionality take a look341 * at [express-params](http://github.com/visionmedia/express-params).342 *343 * @param {String|Array|Function} name344 * @param {Function} fn345 * @return {Server} for chaining346 * @api public347 */348349app.param = function(name, fn){350 var self = this351 , fns = [].slice.call(arguments, 1);352353 // array354 if (Array.isArray(name)) {355 name.forEach(function(name){356 fns.forEach(function(fn){357 self.param(name, fn);358 });359 });360 // param logic361 } else if ('function' == typeof name) {362 this.routes.param(name);363 // single364 } else {365 if (':' == name[0]) name = name.substr(1);366 fns.forEach(function(fn){367 self.routes.param(name, fn);368 });369 }370371 return this;372};373374/**375 * Register the given callback `fn` for the given `type`.376 *377 * @param {String} type378 * @param {Function} fn379 * @return {Server} for chaining380 * @api public381 */382383app.is = function(type, fn){384 if (!fn) return this.isCallbacks[type];385 this.isCallbacks[type] = fn;386 return this;387};388389/**390 * Assign `setting` to `val`, or return `setting`'s value.391 * Mounted servers inherit their parent server's settings.392 *393 * @param {String} setting394 * @param {String} val395 * @return {Server|Mixed} for chaining, or the setting value396 * @api public397 */398399app.set = function(setting, val){400 if (val === undefined) {401 if (this.settings.hasOwnProperty(setting)) {402 return this.settings[setting];403 } else if (this.parent) {404 return this.parent.set(setting);405 }406 } else {407 this.settings[setting] = val;408 return this;409 }410};411412/**413 * Check if `setting` is enabled.414 *415 * @param {String} setting416 * @return {Boolean}417 * @api public418 */419420app.enabled = function(setting){421 return !!this.set(setting);422};423424/**425 * Check if `setting` is disabled.426 *427 * @param {String} setting428 * @return {Boolean}429 * @api public430 */431432app.disabled = function(setting){433 return !this.set(setting);434};435436/**437 * Enable `setting`.438 *439 * @param {String} setting440 * @return {Server} for chaining441 * @api public442 */443444app.enable = function(setting){445 return this.set(setting, true);446};447448/**449 * Disable `setting`.450 *451 * @param {String} setting452 * @return {Server} for chaining453 * @api public454 */455456app.disable = function(setting){457 return this.set(setting, false);458};459460/**461 * Redirect `key` to `url`.462 *463 * @param {String} key464 * @param {String} url465 * @return {Server} for chaining466 * @api public467 */468469app.redirect = function(key, url){470 this.redirects[key] = url;471 return this;472};473474/**475 * Configure callback for zero or more envs,476 * when no env is specified that callback will477 * be invoked for all environments. Any combination478 * can be used multiple times, in any order desired.479 *480 * Examples:481 *482 * app.configure(function(){483 * // executed for all envs484 * });485 *486 * app.configure('stage', function(){487 * // executed staging env488 * });489 *490 * app.configure('stage', 'production', function(){491 * // executed for stage and production492 * });493 *494 * @param {String} env...495 * @param {Function} fn496 * @return {Server} for chaining497 * @api public498 */499500app.configure = function(env, fn){501 var envs = 'all'502 , args = toArray(arguments);503 fn = args.pop();504 if (args.length) envs = args;505 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);506 return this;507};508509/**510 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.511 */512513methods.forEach(function(method){514 app[method] = function(path){515 if (1 == arguments.length) return this.routes.lookup(method, path);516 var args = [method].concat(toArray(arguments));517 if (!this.__usedRouter) this.use(this.router);518 return this.routes._route.apply(this.routes, args);519 }520});521522/**523 * Special-cased "all" method, applying the given route `path`,524 * middleware, and callback to _every_ HTTP method.525 *526 * @param {String} path527 * @param {Function} ...528 * @return {Server} for chaining529 * @api public530 */531532app.all = function(path){533 var args = arguments;534 if (1 == args.length) return this.routes.lookup('all', path);535 methods.forEach(function(method){536 if ('all' == method) return;537 app[method].apply(this, args);538 }, this);539 return this;540};541542// del -> delete alias543544app.del = app.delete;545546/**misc refactoringTj Holowaychukbefore adoption294bc8c
line 547why, one step back547 * Render the given `view` name with `options`application.jsTj Holowaychukbefore adoptiond0585bd
lines 548–551why, one step back548 * and a callback accepting an error and the549 * rendered template string.550 *551 * @param {String} viewmisc refactoringTj Holowaychukbefore adoption294bc8c
line 552why, one step back552 * @param {String|Function} options or fnapplication.jsTj Holowaychukbefore adoptiond0585bd
lines 553–556why, one step back553 * @param {Function} fn554 * @api public555 */556misc refactoringTj Holowaychukbefore adoption294bc8c
line 557why, one step back557app.render = function(view, options, fn){application.jsTj Holowaychukbefore adoptiond0585bd
line 558why, one step back558 var self = thismerging res.localsTj Holowaychukbefore adoption98e2c05
line 559why, one step back559 , opts = {}application.jsTj Holowaychukbefore adoptiond0585bd
lines 560–563why, one step back560 , engines = this.engines561 , root = this.set('views') || process.cwd() + '/views';562563 // support callback function as second argmisc refactoringTj Holowaychukbefore adoption294bc8c
lines 564–565why, one step back564 if ('function' == typeof options) {565 fn = options, options = {};application.jsTj Holowaychukbefore adoptiond0585bd
lines 566–568why, one step back566 }567568 // merge app.localsmerging res.localsTj Holowaychukbefore adoption98e2c05
line 569why, one step back569 utils.merge(opts, this.locals);application.jsTj Holowaychukbefore adoptiond0585bd
line 570why, one step back570merging res.localsTj Holowaychukbefore adoption98e2c05
lines 571–579why, one step back571 // merge options.locals572 if (options.locals) {573 utils.merge(opts, options.locals);574 delete opts.locals;575 }576577 // merge options578 utils.merge(opts, options);579application.jsTj Holowaychukbefore adoptiond0585bd
lines 580–584why, one step back580 // join "view engine" if necessary581 var ext = extname(view);582 if (!ext) view += '.' + (ext = this.set('view engine'));583584 // pass .cache to the enginemerging res.localsTj Holowaychukbefore adoption98e2c05
line 585why, one step back585 opts.cache = this.enabled('view cache');application.jsTj Holowaychukbefore adoptiond0585bd
lines 586–591why, one step back586587 // when no extension nor "view engine" is given588 if (!ext) return fn(new Error('failed to find view "' + view + '"'));589590 // render591 try {use app.engines instead of app.cacheTj Holowaychukbefore adoptione904132
line 592why, one step back592 var engine = engines[ext] = engines[ext] || require(ext);merging res.localsTj Holowaychukbefore adoption98e2c05
lines 593–595why, one step back593 opts.filename = join(root, view);594 view = fs.readFileSync(opts.filename, 'utf8');595 engine.render(view, opts, fn);application.jsTj Holowaychukbefore adoptiond0585bd
lines 596–599why, one step back596 } catch (err) {597 fn(err);598 }599};