application.js
This file
Path
lib/application.js
531 lines · 11.3 KiB · JavaScript
Last changed by
Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3360613
History of this fileTake it
1/*!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')14 , middleware = require('./middleware')15 , debug = require('debug')('express:application')16 , View = require('./view')17 , url = require('url')18 , utils = connect.utils19 , path = require('path')20 , http = require('http')21 , join = path.join22 , fs = require('fs');2324/**25 * Application prototype.26 */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');75 debug('booting in %s mode', this.get('env'));7677 // implicit middleware78 this.use(connect.query());79 this.use(middleware.init(this));8081 // app locals82 this.locals = function(obj){83 for (var key in obj) self.locals[key] = obj[key];84 return self;85 };8687 // response locals88 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(){104 this._usedRouter = true;105 this._router.caseSensitive = this.enabled('case sensitive routing');106 this._router.strict = this.enabled('strict routing');107 return this._router.middleware;108 });109110 // default locals111 this.locals.settings = this.settings;112113 // default configuration114 this.configure('development', function(){115 this.set('json spaces', 2);116 });117118 this.configure('production', function(){119 this.enable('view cache');120 });121};122123/**124 * Remove routes matching the given `path`.125 *126 * @param {Route} path127 * @return {Boolean}128 * @api public129 */130131app.remove = function(path){132 return this._router.lookup('all', path).remove();133};134135/**136 * Lookup routes defined with a path137 * equivalent to `path`.138 *139 * @param {String} path140 * @return {Array}141 * @api public142 */143144app.lookup = function(path){145 return this._router.lookup('all', path);146};147148/**149 * Proxy `connect#use()` to apply settings to150 * mounted applications.151 *152 * @param {String|Function|Server} route153 * @param {Function|Server} fn154 * @return {app} for chaining155 * @api public156 */157158app.use = function(route, fn){159 var app, home, handle;160161 // default route to '/'162 if ('string' != typeof route) fn = route, route = '/';163164 // express app165 if (fn.handle && fn.set) app = fn;166167 // restore .app property on req and res168 if (app) {169 app.route = route;170 fn = function(req, res, next) {171 var orig = req.app;172 app.handle(req, res, function(err){173 req.app = res.app = orig;174 next(err);175 });176 };177 }178179 debug('use %s %s', route, fn.name || 'unnamed');180 connect.proto.use.call(this, route, fn);181182 // mounted an app183 if (app) {184 app.parent = this;185 app.emit('mount', this);186 }187188 return this;189};190191/**192 * Register the given template engine callback `fn`193 * as `ext`. For example we may wish to map ".html"194 * files to ejs rather than using the ".ejs" extension.195 *196 * app.engine('.html', require('ejs').render);197 *198 * or199 *200 * app.engine('html', require('ejs').render);201 *202 * @param {String} ext203 * @param {Function} fn204 * @return {app} for chaining205 * @api public206 */207208app.engine = function(ext, fn){209 if ('.' != ext[0]) ext = '.' + ext;210 this.engines[ext] = fn;211 return this;212};213214/**215 * Map the given param placeholder `name`(s) to the given callback(s).216 *217 * Param mapping is used to provide pre-conditions to routes218 * which us normalized placeholders. This callback has the same219 * signature as regular middleware, for example below when ":userId"220 * is used this function will be invoked in an attempt to load the user.221 *222 * app.param('userId', function(req, res, next, id){223 * User.find(id, function(err, user){224 * if (err) {225 * next(err);226 * } else if (user) {227 * req.user = user;228 * next();229 * } else {230 * next(new Error('failed to load user'));231 * }232 * });233 * });234 *235 * Passing a single function allows you to map logic236 * to the values passed to `app.param()`, for example237 * this is useful to provide coercion support in a concise manner.238 *239 * The following example maps regular expressions to param values240 * ensuring that they match, otherwise passing control to the next241 * route:242 *243 * app.param(function(name, regexp){244 * if (regexp instanceof RegExp) {245 * return function(req, res, next, val){246 * var captures;247 * if (captures = regexp.exec(String(val))) {248 * req.params[name] = captures;249 * next();250 * } else {251 * next('route');252 * }253 * }254 * }255 * });256 *257 * We can now use it as shown below, where "/commit/:commit" expects258 * that the value for ":commit" is at 5 or more digits. The capture259 * groups are then available as `req.params.commit` as we defined260 * in the function above.261 *262 * app.param('commit', /^\d{5,}$/);263 *264 * For more of this useful functionality take a look265 * at [express-params](http://github.com/visionmedia/express-params).266 *267 * @param {String|Array|Function} name268 * @param {Function} fn269 * @return {app} for chaining270 * @api public271 */272273app.param = function(name, fn){274 var self = this275 , fns = [].slice.call(arguments, 1);276277 // array278 if (Array.isArray(name)) {279 name.forEach(function(name){280 fns.forEach(function(fn){281 self.param(name, fn);282 });283 });284 // param logic285 } else if ('function' == typeof name) {286 this._router.param(name);287 // single288 } else {289 if (':' == name[0]) name = name.substr(1);290 fns.forEach(function(fn){291 self._router.param(name, fn);292 });293 }294295 return this;296};297298/**299 * Assign `setting` to `val`, or return `setting`'s value.300 * Mounted servers inherit their parent server's settings.301 *302 * @param {String} setting303 * @param {String} val304 * @return {Server|Mixed} for chaining, or the setting value305 * @api public306 */307308app.set = function(setting, val){309 if (1 == arguments.length) {310 if (this.settings.hasOwnProperty(setting)) {311 return this.settings[setting];312 } else if (this.parent) {313 return this.parent.set(setting);314 }315 } else {316 this.settings[setting] = val;317 return this;318 }319};320321/**322 * Return the app's absolute pathname323 * based on the parent(s) that have324 * mounted it.325 *326 * @return {String}327 * @api private328 */329330app.path = function(){331 return this.parent332 ? this.parent.path() + this.route333 : '';334};335336/**337 * Check if `setting` is enabled.338 *339 * @param {String} setting340 * @return {Boolean}341 * @api public342 */343344app.enabled = function(setting){345 return !!this.set(setting);346};347348/**349 * Check if `setting` is disabled.350 *351 * @param {String} setting352 * @return {Boolean}353 * @api public354 */355356app.disabled = function(setting){357 return !this.set(setting);358};359360/**361 * Enable `setting`.362 *363 * @param {String} setting364 * @return {app} for chaining365 * @api public366 */367368app.enable = function(setting){369 return this.set(setting, true);370};371372/**373 * Disable `setting`.374 *375 * @param {String} setting376 * @return {app} for chaining377 * @api public378 */379380app.disable = function(setting){381 return this.set(setting, false);382};383384/**385 * Configure callback for zero or more envs,386 * when no env is specified that callback will387 * be invoked for all environments. Any combination388 * can be used multiple times, in any order desired.389 *390 * Examples:391 *392 * app.configure(function(){393 * // executed for all envs394 * });395 *396 * app.configure('stage', function(){397 * // executed staging env398 * });399 *400 * app.configure('stage', 'production', function(){401 * // executed for stage and production402 * });403 *404 * @param {String} env...405 * @param {Function} fn406 * @return {app} for chaining407 * @api public408 */409410app.configure = function(env, fn){411 var envs = 'all'412 , args = [].slice.call(arguments);413 fn = args.pop();414 if (args.length) envs = args;415 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);416 return this;417};418419/**420 * Listen for connections.421 *422 * This method takes the same arguments423 * as node's `http.Server#listen()`. 424 *425 * @return {http.Server}426 * @api public427 */428429app.listen = function(){430 var server = http.createServer(this);431 return server.listen.apply(server, arguments);432};433434/**435 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.436 */437438methods.forEach(function(method){439 app[method] = function(path){440 if ('get' == method && 1 == arguments.length) return this.set(path); 441 var args = [method].concat([].slice.call(arguments));442 if (!this._usedRouter) this.use(this.router);443 return this._router.route.apply(this._router, args);444 }445});446447/**448 * Special-cased "all" method, applying the given route `path`,449 * middleware, and callback to _every_ HTTP method.450 *451 * @param {String} path452 * @param {Function} ...453 * @return {app} for chaining454 * @api public455 */456457app.all = function(path){458 var args = arguments;459 methods.forEach(function(method){460 if ('all' == method || 'del' == method) return;461 app[method].apply(this, args);462 }, this);463 return this;464};465466// del -> delete alias467468app.del = app.delete;469470/**471 * Render the given view `name` name with `options`472 * and a callback accepting an error and the473 * rendered template string.474 *475 * @param {String} name476 * @param {String|Function} options or fn477 * @param {Function} fn478 * @api public479 */480481app.render = function(name, options, fn){482 var self = this483 , opts = {}484 , cache = this.cache485 , engines = this.engines486 , view;487488 // support callback function as second arg489 if ('function' == typeof options) {490 fn = options, options = {};491 }492493 // merge app.locals494 utils.merge(opts, this.locals);495496 // merge options.locals497 if (options.locals) {498 utils.merge(opts, options.locals);499 delete opts.locals;500 }501502 // merge options503 utils.merge(opts, options);504505 // set .cache unless explicitly provided506 opts.cache = null == opts.cache507 ? this.enabled('view cache')508 : opts.cache;509510 // primed cache511 if (opts.cache) view = cache[name];512513 // view514 if (!view) {515 view = new View(name, {516 defaultEngine: this.get('view engine')517 , root: this.get('views') || process.cwd() + '/views'518 , engines: engines519 });520521 // prime the cache522 if (opts.cache) cache[name] = view;523 }524525 // render526 try {527 view.render(opts, fn);528 } catch (err) {529 fn(err);530 }531};