application.js
This file
Path
lib/application.js
562 lines · 11.7 KiB · JavaScript
Last changed by
.parent testsTj Holowaychukbefore adoption5d593f2
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 , methods = Router.methods.concat('del', 'all')15 , middleware = require('./middleware')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')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._router.lookup(method, path);55 };5657 self.match[method] = function(path){58 return self._router.match(method, path);59 };6061 self.remove[method] = function(path){62 return self._router.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('root', '/');83 this.set('env', process.env.NODE_ENV || 'development');8485 // implicit middleware86 this.use(connect.query());87 this.use(middleware.init(this));8889 // app locals90 this.locals = function(obj){91 for (var key in obj) self.locals[key] = obj[key];92 return self;93 };9495 // response locals96 this.locals.use = function(fn){97 if (3 == fn.length) {98 self.viewCallbacks.push(fn);99 } else {100 self.viewCallbacks.push(function(req, res, done){101 fn(req, res);102 done();103 });104 }105 return this;106 };107108 // router109 this._router = new Router(this);110 this.routes = this._router.routes;111 this.__defineGetter__('router', function(){112 this._usedRouter = true;113 return self._router.middleware;114 });115116 // default locals117 this.locals.settings = this.settings;118119 // default production configuration120 this.configure('production', function(){121 this.enable('view cache');122 });123};124125/**126 * Remove routes matching the given `path`.127 *128 * @param {Route} path129 * @return {Boolean}130 * @api public131 */132133app.remove = function(path){134 return this._router.lookup('all', path).remove();135};136137/**138 * Lookup routes defined with a path139 * equivalent to `path`.140 *141 * @param {Stirng} path142 * @return {Array}143 * @api public144 */145146app.lookup = function(path){147 return this._router.lookup('all', path);148};149150/**151 * Lookup routes matching the given `url`.152 *153 * @param {Stirng} url154 * @return {Array}155 * @api public156 */157158app.match = function(url){159 return this._router.match('all', url);160};161162/**163 * Proxy `connect#use()` to apply settings to164 * mounted applications.165 *166 * @param {String|Function|Server} route167 * @param {Function|Server} fn168 * @return {app} for chaining169 * @api public170 */171172app.use = function(route, fn){173 var app, home, handle;174175 if ('string' != typeof route) fn = route, route = '/';176177 // express app178 if (fn.handle && fn.set) app = fn;179180 // restore .app property on req and res181 if (app) {182 app.route = route;183 fn = function(req, res, next) {184 var orig = req.app;185 app.handle(req, res, function(err){186 req.app = res.app = orig;187 next(err);188 });189 };190 }191192 connect.proto.use.call(this, route, fn);193194 // mounted an app, emit "mount"195 // and adjust some settings196 if (app) {197 var root = this.get('root') || this.route;198 if ('/' == root) root = '';199 root = root + (app.get('root') || app.route);200 app.set('root', root);201 app.parent = this;202 app.emit('mount', this);203 }204205 return this;206};207208/**209 * Register the given template engine callback `fn`210 * as `ext`. For example we may wish to map ".html"211 * files to ejs rather than using the ".ejs" extension.212 *213 * app.engine('.html', require('ejs').render);214 *215 * or216 *217 * app.engine('html', require('ejs').render);218 *219 * @param {String} ext220 * @param {Function} fn221 * @return {app} for chaining222 * @api public223 */224225app.engine = function(ext, fn){226 if ('.' != ext[0]) ext = '.' + ext;227 this.engines[ext] = fn;228 return this;229};230231/**232 * Map the given param placeholder `name`(s) to the given callback(s).233 *234 * Param mapping is used to provide pre-conditions to routes235 * which us normalized placeholders. This callback has the same236 * signature as regular middleware, for example below when ":userId"237 * is used this function will be invoked in an attempt to load the user.238 *239 * app.param('userId', function(req, res, next, id){240 * User.find(id, function(err, user){241 * if (err) {242 * next(err);243 * } else if (user) {244 * req.user = user;245 * next();246 * } else {247 * next(new Error('failed to load user'));248 * }249 * });250 * });251 *252 * Passing a single function allows you to map logic253 * to the values passed to `app.param()`, for example254 * this is useful to provide coercion support in a concise manner.255 *256 * The following example maps regular expressions to param values257 * ensuring that they match, otherwise passing control to the next258 * route:259 *260 * app.param(function(name, regexp){261 * if (regexp instanceof RegExp) {262 * return function(req, res, next, val){263 * var captures;264 * if (captures = regexp.exec(String(val))) {265 * req.params[name] = captures;266 * next();267 * } else {268 * next('route');269 * }270 * }271 * }272 * });273 *274 * We can now use it as shown below, where "/commit/:commit" expects275 * that the value for ":commit" is at 5 or more digits. The capture276 * groups are then available as `req.params.commit` as we defined277 * in the function above.278 *279 * app.param('commit', /^\d{5,}$/);280 *281 * For more of this useful functionality take a look282 * at [express-params](http://github.com/visionmedia/express-params).283 *284 * @param {String|Array|Function} name285 * @param {Function} fn286 * @return {app} for chaining287 * @api public288 */289290app.param = function(name, fn){291 var self = this292 , fns = [].slice.call(arguments, 1);293294 // array295 if (Array.isArray(name)) {296 name.forEach(function(name){297 fns.forEach(function(fn){298 self.param(name, fn);299 });300 });301 // param logic302 } else if ('function' == typeof name) {303 this._router.param(name);304 // single305 } else {306 if (':' == name[0]) name = name.substr(1);307 fns.forEach(function(fn){308 self._router.param(name, fn);309 });310 }311312 return this;313};314315/**316 * Register the given callback `fn` for the given `type`.317 *318 * @param {String} type319 * @param {Function} fn320 * @return {app} for chaining321 * @api public322 */323324app.is = function(type, fn){325 if (!fn) return this.isCallbacks[type];326 this.isCallbacks[type] = fn;327 return this;328};329330/**331 * Assign `setting` to `val`, or return `setting`'s value.332 * Mounted servers inherit their parent server's settings.333 *334 * @param {String} setting335 * @param {String} val336 * @return {Server|Mixed} for chaining, or the setting value337 * @api public338 */339340app.set = function(setting, val){341 if (val === undefined) {342 if (this.settings.hasOwnProperty(setting)) {343 return this.settings[setting];344 } else if (this.parent) {345 return this.parent.set(setting);346 }347 } else {348 this.settings[setting] = val;349 return this;350 }351};352353/**354 * Check if `setting` is enabled.355 *356 * @param {String} setting357 * @return {Boolean}358 * @api public359 */360361app.enabled = function(setting){362 return !!this.set(setting);363};364365/**366 * Check if `setting` is disabled.367 *368 * @param {String} setting369 * @return {Boolean}370 * @api public371 */372373app.disabled = function(setting){374 return !this.set(setting);375};376377/**378 * Enable `setting`.379 *380 * @param {String} setting381 * @return {app} for chaining382 * @api public383 */384385app.enable = function(setting){386 return this.set(setting, true);387};388389/**390 * Disable `setting`.391 *392 * @param {String} setting393 * @return {app} for chaining394 * @api public395 */396397app.disable = function(setting){398 return this.set(setting, false);399};400401/**402 * Redirect `key` to `url`.403 *404 * @param {String} key405 * @param {String} url406 * @return {app} for chaining407 * @api public408 */409410app.redirect = function(key, url){411 this.redirects[key] = url;412 return this;413};414415/**416 * Configure callback for zero or more envs,417 * when no env is specified that callback will418 * be invoked for all environments. Any combination419 * can be used multiple times, in any order desired.420 *421 * Examples:422 *423 * app.configure(function(){424 * // executed for all envs425 * });426 *427 * app.configure('stage', function(){428 * // executed staging env429 * });430 *431 * app.configure('stage', 'production', function(){432 * // executed for stage and production433 * });434 *435 * @param {String} env...436 * @param {Function} fn437 * @return {app} for chaining438 * @api public439 */440441app.configure = function(env, fn){442 var envs = 'all'443 , args = [].slice.call(arguments);444 fn = args.pop();445 if (args.length) envs = args;446 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);447 return this;448};449450/**451 * Listen for connections.452 *453 * This method takes the same arguments454 * as node's `http.Server#listen()`. 455 *456 * @return {http.Server}457 * @api public458 */459460app.listen = function(){461 var server = http.createServer(this);462 return server.listen.apply(server, arguments);463};464465/**466 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.467 */468469methods.forEach(function(method){470 app[method] = function(path){471 if ('get' == method && 1 == arguments.length) return this.set(path); 472 var args = [method].concat([].slice.call(arguments));473 if (!this._usedRouter) this.use(this.router);474 return this._router._route.apply(this._router, args);475 }476});477478/**479 * Special-cased "all" method, applying the given route `path`,480 * middleware, and callback to _every_ HTTP method.481 *482 * @param {String} path483 * @param {Function} ...484 * @return {app} for chaining485 * @api public486 */487488app.all = function(path){489 var args = arguments;490 methods.forEach(function(method){491 if ('all' == method) return;492 app[method].apply(this, args);493 }, this);494 return this;495};496497// del -> delete alias498499app.del = app.delete;500501/**502 * Render the given view `name` name with `options`503 * and a callback accepting an error and the504 * rendered template string.505 *506 * @param {String} name507 * @param {String|Function} options or fn508 * @param {Function} fn509 * @api public510 */511512app.render = function(name, options, fn){513 var self = this514 , opts = {}515 , cache = this.cache516 , engines = this.engines517 , view;518519 // support callback function as second arg520 if ('function' == typeof options) {521 fn = options, options = {};522 }523524 // merge app.locals525 utils.merge(opts, this.locals);526527 // merge options.locals528 if (options.locals) {529 utils.merge(opts, options.locals);530 delete opts.locals;531 }532533 // merge options534 utils.merge(opts, options);535536 // set .cache unless explicitly provided537 opts.cache = null == opts.cache538 ? this.enabled('view cache')539 : opts.cache;540541 // primed cache542 if (opts.cache) view = cache[name];543544 // view545 if (!view) {546 view = new View(name, {547 defaultEngine: this.get('view engine')548 , root: this.get('views') || process.cwd() + '/views'549 , engines: engines550 });551552 // prime the cache553 if (opts.cache) cache[name] = view;554 }555556 // render557 try {558 view.render(opts, fn);559 } catch (err) {560 fn(err);561 }562};