application.js
This file
Path
lib/application.js
590 lines · 12.3 KiB · JavaScript
Last changed by
Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
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 , View = require('./view')16 , url = require('url')17 , utils = connect.utils18 , path = require('path')19 , join = path.join20 , fs = require('fs')21 , qs = require('qs');2223/**24 * Expose `HTTPServer`.25 */2627var app = exports = module.exports = {};2829/**30 * Initialize the server.31 *32 * - setup default configuration33 * - setup default middleware34 * - setup route reflection methods35 *36 * @api private37 */3839app.init = function(){40 var self = this;41 this.cache = {};42 this.settings = {};43 this.engines = {};44 this.redirects = {};45 this.isCallbacks = {};46 this.viewCallbacks = [];47 this.defaultConfiguration();4849 // route reflection methods50 methods.forEach(function(method){51 self.lookup[method] = function(path){52 return self._router.lookup(method, path);53 };5455 self.match[method] = function(path){56 return self._router.match(method, path);57 };5859 self.remove[method] = function(path){60 return self._router.lookup(method, path).remove();61 };62 });6364 // del -> delete65 self.lookup.del = self.lookup.delete;66 self.match.del = self.match.delete;67 self.remove.del = self.remove.delete;68};6970/**71 * Initialize application configuration.72 *73 * @api private74 */7576app.defaultConfiguration = function(){77 var self = this;7879 // default settings80 this.set('root', '/');81 this.set('env', process.env.NODE_ENV || 'development');8283 // always parse req.query84 this.use(connect.query());8586 this.locals = function(obj){87 for (var key in obj) self.locals[key] = obj[key];88 return self;89 };9091 this.locals.use = function(fn){92 if (3 == fn.length) {93 self.viewCallbacks.push(fn);94 } else {95 self.viewCallbacks.push(function(req, res, done){96 fn(req, res);97 done();98 });99 }100 return this;101 };102103 // expose objects to each other104 this.use(function(req, res, next){105 var charset;106 res.setHeader('X-Powered-By', 'Express');107 req.app = res.app = self;108 req.res = res;109 res.req = req;110 req.next = next;111112 req.__proto__ = self.request;113 res.__proto__ = self.response;114115 res.locals = function(obj){116 for (var key in obj) res.locals[key] = obj[key];117 return res;118 };119120 next();121 });122123 // router124 this._router = new Router(this);125 this.routes = this._router.routes;126 this.__defineGetter__('router', function(){127 this._usedRouter = true;128 return self._router.middleware;129 });130131 // default locals132 this.locals.settings = this.settings;133134 // default production configuration135 this.configure('production', function(){136 this.enable('view cache');137 });138};139140/**141 * Remove routes matching the given `path`.142 *143 * @param {Route} path144 * @return {Boolean}145 * @api public146 */147148app.remove = function(path){149 return this._router.lookup('all', path).remove();150};151152/**153 * Lookup routes defined with a path154 * equivalent to `path`.155 *156 * @param {Stirng} path157 * @return {Array}158 * @api public159 */160161app.lookup = function(path){162 return this._router.lookup('all', path);163};164165/**166 * Lookup routes matching the given `url`.167 *168 * @param {Stirng} url169 * @return {Array}170 * @api public171 */172173app.match = function(url){174 return this._router.match('all', url);175};176177/**178 * Proxy `connect#use()` to apply settings to179 * mounted applications.180 *181 * @param {String|Function|Server} route182 * @param {Function|Server} middleware183 * @return {Server} for chaining184 * @api public185 */186187app.use = function(route, middleware){188 var app, home, handle;189190 if ('string' != typeof route) {191 middleware = route, route = '/';192 }193194 // express app195 if (middleware.handle && middleware.set) app = middleware;196197 // restore .app property on req and res198 if (app) {199 app.route = route;200 middleware = function(req, res, next) {201 var orig = req.app;202 app.handle(req, res, function(err){203 req.app = res.app = orig;204 next(err);205 });206 };207 }208209 connect.proto.use.call(this, route, middleware);210211 // mounted an app, invoke the hook212 // and adjust some settings213 if (app) {214 var root = this.get('root') || this.route;215 if ('/' == root) root = '';216 root = root + (app.get('root') || app.route);217 app.set('root', root);218 app.parent = this;219 if (app.__mounted) app.__mounted.call(app, this);220 }221222 return this;223};224225/**226 * Assign a callback `fn` which is called227 * when this `Server` is passed to `Server#use()`.228 *229 * Examples:230 *231 * var app = express.createServer()232 * , blog = express.createServer();233 *234 * blog.mounted(function(parent){235 * // parent is app236 * // "this" is blog237 * });238 *239 * app.use(blog);240 *241 * @param {Function} fn242 * @return {Server} for chaining243 * @api public244 */245246app.mounted = function(fn){247 this.__mounted = fn;248 return this;249};250251/**252 * Register the given template engine callback `fn`253 * as `ext`. For example we may wish to map ".html"254 * files to ejs rather than using the ".ejs" extension.255 *256 * app.engine('.html', require('ejs').render);257 *258 * or259 *260 * app.engine('html', require('ejs').render);261 *262 * @param {String} ext263 * @param {Function} fn264 * @return {Server} for chaining265 * @api public266 */267268app.engine = function(ext, fn){269 if ('.' != ext[0]) ext = '.' + ext;270 this.engines[ext] = fn;271 return this;272};273274/**275 * Map the given param placeholder `name`(s) to the given callback(s).276 *277 * Param mapping is used to provide pre-conditions to routes278 * which us normalized placeholders. This callback has the same279 * signature as regular middleware, for example below when ":userId"280 * is used this function will be invoked in an attempt to load the user.281 *282 * app.param('userId', function(req, res, next, id){283 * User.find(id, function(err, user){284 * if (err) {285 * next(err);286 * } else if (user) {287 * req.user = user;288 * next();289 * } else {290 * next(new Error('failed to load user'));291 * }292 * });293 * });294 *295 * Passing a single function allows you to map logic296 * to the values passed to `app.param()`, for example297 * this is useful to provide coercion support in a concise manner.298 *299 * The following example maps regular expressions to param values300 * ensuring that they match, otherwise passing control to the next301 * route:302 *303 * app.param(function(name, regexp){304 * if (regexp instanceof RegExp) {305 * return function(req, res, next, val){306 * var captures;307 * if (captures = regexp.exec(String(val))) {308 * req.params[name] = captures;309 * next();310 * } else {311 * next('route');312 * }313 * }314 * }315 * });316 *317 * We can now use it as shown below, where "/commit/:commit" expects318 * that the value for ":commit" is at 5 or more digits. The capture319 * groups are then available as `req.params.commit` as we defined320 * in the function above.321 *322 * app.param('commit', /^\d{5,}$/);323 *324 * For more of this useful functionality take a look325 * at [express-params](http://github.com/visionmedia/express-params).326 *327 * @param {String|Array|Function} name328 * @param {Function} fn329 * @return {Server} for chaining330 * @api public331 */332333app.param = function(name, fn){334 var self = this335 , fns = [].slice.call(arguments, 1);336337 // array338 if (Array.isArray(name)) {339 name.forEach(function(name){340 fns.forEach(function(fn){341 self.param(name, fn);342 });343 });344 // param logic345 } else if ('function' == typeof name) {346 this._router.param(name);347 // single348 } else {349 if (':' == name[0]) name = name.substr(1);350 fns.forEach(function(fn){351 self._router.param(name, fn);352 });353 }354355 return this;356};357358/**359 * Register the given callback `fn` for the given `type`.360 *361 * @param {String} type362 * @param {Function} fn363 * @return {Server} for chaining364 * @api public365 */366367app.is = function(type, fn){368 if (!fn) return this.isCallbacks[type];369 this.isCallbacks[type] = fn;370 return this;371};372373/**374 * Assign `setting` to `val`, or return `setting`'s value.375 * Mounted servers inherit their parent server's settings.376 *377 * @param {String} setting378 * @param {String} val379 * @return {Server|Mixed} for chaining, or the setting value380 * @api public381 */382383app.set = function(setting, val){384 if (val === undefined) {385 if (this.settings.hasOwnProperty(setting)) {386 return this.settings[setting];387 } else if (this.parent) {388 return this.parent.set(setting);389 }390 } else {391 this.settings[setting] = val;392 return this;393 }394};395396/**397 * Check if `setting` is enabled.398 *399 * @param {String} setting400 * @return {Boolean}401 * @api public402 */403404app.enabled = function(setting){405 return !!this.set(setting);406};407408/**409 * Check if `setting` is disabled.410 *411 * @param {String} setting412 * @return {Boolean}413 * @api public414 */415416app.disabled = function(setting){417 return !this.set(setting);418};419420/**421 * Enable `setting`.422 *423 * @param {String} setting424 * @return {Server} for chaining425 * @api public426 */427428app.enable = function(setting){429 return this.set(setting, true);430};431432/**433 * Disable `setting`.434 *435 * @param {String} setting436 * @return {Server} for chaining437 * @api public438 */439440app.disable = function(setting){441 return this.set(setting, false);442};443444/**445 * Redirect `key` to `url`.446 *447 * @param {String} key448 * @param {String} url449 * @return {Server} for chaining450 * @api public451 */452453app.redirect = function(key, url){454 this.redirects[key] = url;455 return this;456};457458/**459 * Configure callback for zero or more envs,460 * when no env is specified that callback will461 * be invoked for all environments. Any combination462 * can be used multiple times, in any order desired.463 *464 * Examples:465 *466 * app.configure(function(){467 * // executed for all envs468 * });469 *470 * app.configure('stage', function(){471 * // executed staging env472 * });473 *474 * app.configure('stage', 'production', function(){475 * // executed for stage and production476 * });477 *478 * @param {String} env...479 * @param {Function} fn480 * @return {Server} for chaining481 * @api public482 */483484app.configure = function(env, fn){485 var envs = 'all'486 , args = [].slice.call(arguments);487 fn = args.pop();488 if (args.length) envs = args;489 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);490 return this;491};492493/**494 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.495 */496497methods.forEach(function(method){498 app[method] = function(path){499 if ('get' == method && 1 == arguments.length) return this.set(path); 500 var args = [method].concat([].slice.call(arguments));501 if (!this._usedRouter) this.use(this.router);502 return this._router._route.apply(this._router, args);503 }504});505506/**507 * Special-cased "all" method, applying the given route `path`,508 * middleware, and callback to _every_ HTTP method.509 *510 * @param {String} path511 * @param {Function} ...512 * @return {Server} for chaining513 * @api public514 */515516app.all = function(path){517 var args = arguments;518 methods.forEach(function(method){519 if ('all' == method) return;520 app[method].apply(this, args);521 }, this);522 return this;523};524525// del -> delete alias526527app.del = app.delete;528529/**530 * Render the given view `name` name with `options`531 * and a callback accepting an error and the532 * rendered template string.533 *534 * @param {String} name535 * @param {String|Function} options or fn536 * @param {Function} fn537 * @api public538 */539540app.render = function(name, options, fn){541 var self = this542 , opts = {}543 , cache = this.cache544 , engines = this.engines545 , view;546547 // support callback function as second arg548 if ('function' == typeof options) {549 fn = options, options = {};550 }551552 // merge app.locals553 utils.merge(opts, this.locals);554555 // merge options.locals556 if (options.locals) {557 utils.merge(opts, options.locals);558 delete opts.locals;559 }560561 // merge options562 utils.merge(opts, options);563564 // set .cache unless explicitly provided565 opts.cache = null == opts.cache566 ? this.enabled('view cache')567 : opts.cache;568569 // primed cache570 if (opts.cache) view = cache[name];571572 // view573 if (!view) {574 view = new View(name, {575 defaultEngine: this.get('view engine')576 , root: this.get('views') || process.cwd() + '/views'577 , engines: engines578 });579580 // prime the cache581 if (opts.cache) cache[name] = view;582 }583584 // render585 try {586 view.render(opts, fn);587 } catch (err) {588 fn(err);589 }590};