application.js
This file
Path
lib/application.js
556 lines · 11.5 KiB · JavaScript
Last changed by
removed "root" settingTj Holowaychukbefore adoption87b991c
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('env', process.env.NODE_ENV || 'development');8384 // implicit middleware85 this.use(connect.query());86 this.use(middleware.init(this));8788 // app locals89 this.locals = function(obj){90 for (var key in obj) self.locals[key] = obj[key];91 return self;92 };9394 // response locals95 this.locals.use = function(fn){96 if (3 == fn.length) {97 self.viewCallbacks.push(fn);98 } else {99 self.viewCallbacks.push(function(req, res, done){100 fn(req, res);101 done();102 });103 }104 return this;105 };106107 // router108 this._router = new Router(this);109 this.routes = this._router.routes;110 this.__defineGetter__('router', function(){111 this._usedRouter = true;112 return self._router.middleware;113 });114115 // default locals116 this.locals.settings = this.settings;117118 // default production configuration119 this.configure('production', function(){120 this.enable('view cache');121 });122};123124/**125 * Remove routes matching the given `path`.126 *127 * @param {Route} path128 * @return {Boolean}129 * @api public130 */131132app.remove = function(path){133 return this._router.lookup('all', path).remove();134};135136/**137 * Lookup routes defined with a path138 * equivalent to `path`.139 *140 * @param {Stirng} path141 * @return {Array}142 * @api public143 */144145app.lookup = function(path){146 return this._router.lookup('all', path);147};148149/**150 * Lookup routes matching the given `url`.151 *152 * @param {Stirng} url153 * @return {Array}154 * @api public155 */156157app.match = function(url){158 return this._router.match('all', url);159};160161/**162 * Proxy `connect#use()` to apply settings to163 * mounted applications.164 *165 * @param {String|Function|Server} route166 * @param {Function|Server} fn167 * @return {app} for chaining168 * @api public169 */170171app.use = function(route, fn){172 var app, home, handle;173174 if ('string' != typeof route) fn = route, route = '/';175176 // express app177 if (fn.handle && fn.set) app = fn;178179 // restore .app property on req and res180 if (app) {181 app.route = route;182 fn = function(req, res, next) {183 var orig = req.app;184 app.handle(req, res, function(err){185 req.app = res.app = orig;186 next(err);187 });188 };189 }190191 connect.proto.use.call(this, route, fn);192193 // mounted an app194 if (app) {195 app.parent = this;196 app.emit('mount', this);197 }198199 return this;200};201202/**203 * Register the given template engine callback `fn`204 * as `ext`. For example we may wish to map ".html"205 * files to ejs rather than using the ".ejs" extension.206 *207 * app.engine('.html', require('ejs').render);208 *209 * or210 *211 * app.engine('html', require('ejs').render);212 *213 * @param {String} ext214 * @param {Function} fn215 * @return {app} for chaining216 * @api public217 */218219app.engine = function(ext, fn){220 if ('.' != ext[0]) ext = '.' + ext;221 this.engines[ext] = fn;222 return this;223};224225/**226 * Map the given param placeholder `name`(s) to the given callback(s).227 *228 * Param mapping is used to provide pre-conditions to routes229 * which us normalized placeholders. This callback has the same230 * signature as regular middleware, for example below when ":userId"231 * is used this function will be invoked in an attempt to load the user.232 *233 * app.param('userId', function(req, res, next, id){234 * User.find(id, function(err, user){235 * if (err) {236 * next(err);237 * } else if (user) {238 * req.user = user;239 * next();240 * } else {241 * next(new Error('failed to load user'));242 * }243 * });244 * });245 *246 * Passing a single function allows you to map logic247 * to the values passed to `app.param()`, for example248 * this is useful to provide coercion support in a concise manner.249 *250 * The following example maps regular expressions to param values251 * ensuring that they match, otherwise passing control to the next252 * route:253 *254 * app.param(function(name, regexp){255 * if (regexp instanceof RegExp) {256 * return function(req, res, next, val){257 * var captures;258 * if (captures = regexp.exec(String(val))) {259 * req.params[name] = captures;260 * next();261 * } else {262 * next('route');263 * }264 * }265 * }266 * });267 *268 * We can now use it as shown below, where "/commit/:commit" expects269 * that the value for ":commit" is at 5 or more digits. The capture270 * groups are then available as `req.params.commit` as we defined271 * in the function above.272 *273 * app.param('commit', /^\d{5,}$/);274 *275 * For more of this useful functionality take a look276 * at [express-params](http://github.com/visionmedia/express-params).277 *278 * @param {String|Array|Function} name279 * @param {Function} fn280 * @return {app} for chaining281 * @api public282 */283284app.param = function(name, fn){285 var self = this286 , fns = [].slice.call(arguments, 1);287288 // array289 if (Array.isArray(name)) {290 name.forEach(function(name){291 fns.forEach(function(fn){292 self.param(name, fn);293 });294 });295 // param logic296 } else if ('function' == typeof name) {297 this._router.param(name);298 // single299 } else {300 if (':' == name[0]) name = name.substr(1);301 fns.forEach(function(fn){302 self._router.param(name, fn);303 });304 }305306 return this;307};308309/**310 * Register the given callback `fn` for the given `type`.311 *312 * @param {String} type313 * @param {Function} fn314 * @return {app} for chaining315 * @api public316 */317318app.is = function(type, fn){319 if (!fn) return this.isCallbacks[type];320 this.isCallbacks[type] = fn;321 return this;322};323324/**325 * Assign `setting` to `val`, or return `setting`'s value.326 * Mounted servers inherit their parent server's settings.327 *328 * @param {String} setting329 * @param {String} val330 * @return {Server|Mixed} for chaining, or the setting value331 * @api public332 */333334app.set = function(setting, val){335 if (val === undefined) {336 if (this.settings.hasOwnProperty(setting)) {337 return this.settings[setting];338 } else if (this.parent) {339 return this.parent.set(setting);340 }341 } else {342 this.settings[setting] = val;343 return this;344 }345};346347/**348 * Check if `setting` is enabled.349 *350 * @param {String} setting351 * @return {Boolean}352 * @api public353 */354355app.enabled = function(setting){356 return !!this.set(setting);357};358359/**360 * Check if `setting` is disabled.361 *362 * @param {String} setting363 * @return {Boolean}364 * @api public365 */366367app.disabled = function(setting){368 return !this.set(setting);369};370371/**372 * Enable `setting`.373 *374 * @param {String} setting375 * @return {app} for chaining376 * @api public377 */378379app.enable = function(setting){380 return this.set(setting, true);381};382383/**384 * Disable `setting`.385 *386 * @param {String} setting387 * @return {app} for chaining388 * @api public389 */390391app.disable = function(setting){392 return this.set(setting, false);393};394395/**396 * Redirect `key` to `url`.397 *398 * @param {String} key399 * @param {String} url400 * @return {app} for chaining401 * @api public402 */403404app.redirect = function(key, url){405 this.redirects[key] = url;406 return this;407};408409/**410 * Configure callback for zero or more envs,411 * when no env is specified that callback will412 * be invoked for all environments. Any combination413 * can be used multiple times, in any order desired.414 *415 * Examples:416 *417 * app.configure(function(){418 * // executed for all envs419 * });420 *421 * app.configure('stage', function(){422 * // executed staging env423 * });424 *425 * app.configure('stage', 'production', function(){426 * // executed for stage and production427 * });428 *429 * @param {String} env...430 * @param {Function} fn431 * @return {app} for chaining432 * @api public433 */434435app.configure = function(env, fn){436 var envs = 'all'437 , args = [].slice.call(arguments);438 fn = args.pop();439 if (args.length) envs = args;440 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);441 return this;442};443444/**445 * Listen for connections.446 *447 * This method takes the same arguments448 * as node's `http.Server#listen()`. 449 *450 * @return {http.Server}451 * @api public452 */453454app.listen = function(){455 var server = http.createServer(this);456 return server.listen.apply(server, arguments);457};458459/**460 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.461 */462463methods.forEach(function(method){464 app[method] = function(path){465 if ('get' == method && 1 == arguments.length) return this.set(path); 466 var args = [method].concat([].slice.call(arguments));467 if (!this._usedRouter) this.use(this.router);468 return this._router._route.apply(this._router, args);469 }470});471472/**473 * Special-cased "all" method, applying the given route `path`,474 * middleware, and callback to _every_ HTTP method.475 *476 * @param {String} path477 * @param {Function} ...478 * @return {app} for chaining479 * @api public480 */481482app.all = function(path){483 var args = arguments;484 methods.forEach(function(method){485 if ('all' == method) return;486 app[method].apply(this, args);487 }, this);488 return this;489};490491// del -> delete alias492493app.del = app.delete;494495/**496 * Render the given view `name` name with `options`497 * and a callback accepting an error and the498 * rendered template string.499 *500 * @param {String} name501 * @param {String|Function} options or fn502 * @param {Function} fn503 * @api public504 */505506app.render = function(name, options, fn){507 var self = this508 , opts = {}509 , cache = this.cache510 , engines = this.engines511 , view;512513 // support callback function as second arg514 if ('function' == typeof options) {515 fn = options, options = {};516 }517518 // merge app.locals519 utils.merge(opts, this.locals);520521 // merge options.locals522 if (options.locals) {523 utils.merge(opts, options.locals);524 delete opts.locals;525 }526527 // merge options528 utils.merge(opts, options);529530 // set .cache unless explicitly provided531 opts.cache = null == opts.cache532 ? this.enabled('view cache')533 : opts.cache;534535 // primed cache536 if (opts.cache) view = cache[name];537538 // view539 if (!view) {540 view = new View(name, {541 defaultEngine: this.get('view engine')542 , root: this.get('views') || process.cwd() + '/views'543 , engines: engines544 });545546 // prime the cache547 if (opts.cache) cache[name] = view;548 }549550 // render551 try {552 view.render(opts, fn);553 } catch (err) {554 fn(err);555 }556};