application.js
This file
Path
lib/application.js
585 lines · 12.3 KiB · JavaScript
Last changed by
app.locals.use(fn)Tj Holowaychukbefore adoption0f6ad43
History of this fileTake it
12/*!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 , View = require('./view')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 *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.redirects = {};47 this.isCallbacks = {};48 this.viewCallbacks = [];49 this.defaultConfiguration();5051 // route reflection methods52 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;8081 // default settings82 this.set('home', '/');83 this.set('env', process.env.NODE_ENV || 'development');8485 // always parse req.query86 this.use(connect.query());8788 this.locals = function(obj){89 for (var key in obj) self.locals[key] = obj[key];90 return self;91 };9293 this.locals.use = function(fn){94 self.viewCallbacks.push(fn);95 return this;96 };9798 // expose objects to each other99 this.use(function(req, res, next){100 var charset;101 res.setHeader('X-Powered-By', 'Express');102 req.app = res.app = self;103 req.res = res;104 res.req = req;105 req.next = next;106107 // charset108 if (charset = self.set('charset')) res.charset = charset;109110 res.locals = function(obj){111 for (var key in obj) res.locals[key] = obj[key];112 return res;113 };114115 next();116 });117118 // router119 this.routes = new Router(this);120 this.__defineGetter__('router', function(){121 this.__usedRouter = true;122 return self.routes.middleware;123 });124125 // default locals126 this.locals.settings = this.settings;127128 // default production configuration129 this.configure('production', function(){130 this.enable('view cache');131 });132};133134/**135 * Remove routes matching the given `path`.136 *137 * @param {Route} path138 * @return {Boolean}139 * @api public140 */141142app.remove = function(path){143 return this.routes.lookup('all', path).remove();144};145146/**147 * Lookup routes defined with a path148 * equivalent to `path`.149 *150 * @param {Stirng} path151 * @return {Array}152 * @api public153 */154155app.lookup = function(path){156 return this.routes.lookup('all', path);157};158159/**160 * Lookup routes matching the given `url`.161 *162 * @param {Stirng} url163 * @return {Array}164 * @api public165 */166167app.match = function(url){168 return this.routes.match('all', url);169};170171/**172 * Proxy `connect.HTTPServer#use()` to apply settings to173 * mounted applications.174 *175 * @param {String|Function|Server} route176 * @param {Function|Server} middleware177 * @return {Server} for chaining178 * @api public179 */180181app.use = function(route, middleware){182 var app, home, handle;183184 if ('string' != typeof route) {185 middleware = route, route = '/';186 }187188 // express app189 if (middleware.handle && middleware.set) app = middleware;190191 // restore .app property on req and res192 if (app) {193 app.route = route;194 middleware = function(req, res, next) {195 var orig = req.app;196 app.handle(req, res, function(err){197 req.app = res.app = orig;198 next(err);199 });200 };201 }202203 connect.proto.use.call(this, route, middleware);204205 // mounted an app, invoke the hook206 // and adjust some settings207 if (app) {208 base = this.set('basepath') || this.route;209 if ('/' == base) base = '';210 base = base + (app.set('basepath') || app.route);211 app.set('basepath', base);212 app.parent = this;213 if (app.__mounted) app.__mounted.call(app, this);214 }215216 return this;217};218219/**220 * Assign a callback `fn` which is called221 * when this `Server` is passed to `Server#use()`.222 *223 * Examples:224 *225 * var app = express.createServer()226 * , blog = express.createServer();227 *228 * blog.mounted(function(parent){229 * // parent is app230 * // "this" is blog231 * });232 *233 * app.use(blog);234 *235 * @param {Function} fn236 * @return {Server} for chaining237 * @api public238 */239240app.mounted = function(fn){241 this.__mounted = fn;242 return this;243};244245/**246 * Register the given template engine callback `fn`247 * as `ext`. For example we may wish to map ".html"248 * files to ejs rather than using the ".ejs" extension.249 *250 * app.register('.html', require('ejs').render);251 *252 * or253 *254 * app.register('html', require('ejs').render);255 *256 * @param {String} ext257 * @param {Function} fn258 * @return {Server} for chaining259 * @api public260 */261262app.register = function(ext, fn){263 if ('.' != ext[0]) ext = '.' + ext;264 this.engines[ext] = fn;265 return this;266};267268/**269 * Map the given param placeholder `name`(s) to the given callback(s).270 *271 * Param mapping is used to provide pre-conditions to routes272 * which us normalized placeholders. This callback has the same273 * signature as regular middleware, for example below when ":userId"274 * is used this function will be invoked in an attempt to load the user.275 *276 * app.param('userId', function(req, res, next, id){277 * User.find(id, function(err, user){278 * if (err) {279 * next(err);280 * } else if (user) {281 * req.user = user;282 * next();283 * } else {284 * next(new Error('failed to load user'));285 * }286 * });287 * });288 *289 * Passing a single function allows you to map logic290 * to the values passed to `app.param()`, for example291 * this is useful to provide coercion support in a concise manner.292 *293 * The following example maps regular expressions to param values294 * ensuring that they match, otherwise passing control to the next295 * route:296 *297 * app.param(function(name, regexp){298 * if (regexp instanceof RegExp) {299 * return function(req, res, next, val){300 * var captures;301 * if (captures = regexp.exec(String(val))) {302 * req.params[name] = captures;303 * next();304 * } else {305 * next('route');306 * }307 * }308 * }309 * });310 *311 * We can now use it as shown below, where "/commit/:commit" expects312 * that the value for ":commit" is at 5 or more digits. The capture313 * groups are then available as `req.params.commit` as we defined314 * in the function above.315 *316 * app.param('commit', /^\d{5,}$/);317 *318 * For more of this useful functionality take a look319 * at [express-params](http://github.com/visionmedia/express-params).320 *321 * @param {String|Array|Function} name322 * @param {Function} fn323 * @return {Server} for chaining324 * @api public325 */326327app.param = function(name, fn){328 var self = this329 , fns = [].slice.call(arguments, 1);330331 // array332 if (Array.isArray(name)) {333 name.forEach(function(name){334 fns.forEach(function(fn){335 self.param(name, fn);336 });337 });338 // param logic339 } else if ('function' == typeof name) {340 this.routes.param(name);341 // single342 } else {343 if (':' == name[0]) name = name.substr(1);344 fns.forEach(function(fn){345 self.routes.param(name, fn);346 });347 }348349 return this;350};351352/**353 * Register the given callback `fn` for the given `type`.354 *355 * @param {String} type356 * @param {Function} fn357 * @return {Server} for chaining358 * @api public359 */360361app.is = function(type, fn){362 if (!fn) return this.isCallbacks[type];363 this.isCallbacks[type] = fn;364 return this;365};366367/**368 * Assign `setting` to `val`, or return `setting`'s value.369 * Mounted servers inherit their parent server's settings.370 *371 * @param {String} setting372 * @param {String} val373 * @return {Server|Mixed} for chaining, or the setting value374 * @api public375 */376377app.set = function(setting, val){378 if (val === undefined) {379 if (this.settings.hasOwnProperty(setting)) {380 return this.settings[setting];381 } else if (this.parent) {382 return this.parent.set(setting);383 }384 } else {385 this.settings[setting] = val;386 return this;387 }388};389390/**391 * Check if `setting` is enabled.392 *393 * @param {String} setting394 * @return {Boolean}395 * @api public396 */397398app.enabled = function(setting){399 return !!this.set(setting);400};401402/**403 * Check if `setting` is disabled.404 *405 * @param {String} setting406 * @return {Boolean}407 * @api public408 */409410app.disabled = function(setting){411 return !this.set(setting);412};413414/**415 * Enable `setting`.416 *417 * @param {String} setting418 * @return {Server} for chaining419 * @api public420 */421422app.enable = function(setting){423 return this.set(setting, true);424};425426/**427 * Disable `setting`.428 *429 * @param {String} setting430 * @return {Server} for chaining431 * @api public432 */433434app.disable = function(setting){435 return this.set(setting, false);436};437438/**439 * Redirect `key` to `url`.440 *441 * @param {String} key442 * @param {String} url443 * @return {Server} for chaining444 * @api public445 */446447app.redirect = function(key, url){448 this.redirects[key] = url;449 return this;450};451452/**453 * Configure callback for zero or more envs,454 * when no env is specified that callback will455 * be invoked for all environments. Any combination456 * can be used multiple times, in any order desired.457 *458 * Examples:459 *460 * app.configure(function(){461 * // executed for all envs462 * });463 *464 * app.configure('stage', function(){465 * // executed staging env466 * });467 *468 * app.configure('stage', 'production', function(){469 * // executed for stage and production470 * });471 *472 * @param {String} env...473 * @param {Function} fn474 * @return {Server} for chaining475 * @api public476 */477478app.configure = function(env, fn){479 var envs = 'all'480 , args = toArray(arguments);481 fn = args.pop();482 if (args.length) envs = args;483 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);484 return this;485};486487/**488 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.489 */490491methods.forEach(function(method){492 app[method] = function(path){493 if (1 == arguments.length) return this.routes.lookup(method, path);494 var args = [method].concat(toArray(arguments));495 if (!this.__usedRouter) this.use(this.router);496 return this.routes._route.apply(this.routes, args);497 }498});499500/**501 * Special-cased "all" method, applying the given route `path`,502 * middleware, and callback to _every_ HTTP method.503 *504 * @param {String} path505 * @param {Function} ...506 * @return {Server} for chaining507 * @api public508 */509510app.all = function(path){511 var args = arguments;512 if (1 == args.length) return this.routes.lookup('all', path);513 methods.forEach(function(method){514 if ('all' == method) return;515 app[method].apply(this, args);516 }, this);517 return this;518};519520// del -> delete alias521522app.del = app.delete;523524/**525 * Render the given view `name` name with `options`526 * and a callback accepting an error and the527 * rendered template string.528 *529 * @param {String} name530 * @param {String|Function} options or fn531 * @param {Function} fn532 * @api public533 */534535app.render = function(name, options, fn){536 var self = this537 , opts = {}538 , cache = this.cache539 , engines = this.engines540 , view;541542 // support callback function as second arg543 if ('function' == typeof options) {544 fn = options, options = {};545 }546547 // merge app.locals548 utils.merge(opts, this.locals);549550 // merge options.locals551 if (options.locals) {552 utils.merge(opts, options.locals);553 delete opts.locals;554 }555556 // merge options557 utils.merge(opts, options);558559 // set .cache unless explicitly provided560 opts.cache = null == opts.cache561 ? this.enabled('view cache')562 : opts.cache;563564 // primed cache565 if (opts.cache) view = cache[name];566567 // view568 if (!view) {569 view = new View(name, {570 defaultEngine: this.set('view engine')571 , root: this.set('views') || process.cwd() + '/views'572 , engines: engines573 });574575 // prime the cache576 if (opts.cache) cache[name] = view;577 }578579 // render580 try {581 view.render(opts, fn);582 } catch (err) {583 fn(err);584 }585};