application.js
This file
Path
lib/application.js
612 lines · 13.1 KiB · JavaScript
Last changed by
docsTj Holowaychukbefore adoptioncb2b9fe
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 , url = require('url')18 , utils = connect.utils19 , path = require('path')20 , extname = path.extname21 , 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 * @param {Array} middleware35 * @api private36 */3738app.init = function(middleware){39 var self = this;40 this.cache = {};41 this.settings = {};42 this.engines = {};43 this.redirects = {};44 this.isCallbacks = {};4546 // default settings47 this.set('home', '/');48 this.set('env', process.env.NODE_ENV || 'development');4950 // always parse req.query51 this.use(connect.query());5253 /**54 * Assign several locals with the given `obj`,55 * or return the locals.56 *57 * @param {Object} obj58 * @return {Object|HTTPServer}59 * @api public60 */6162 this.locals = function(obj){63 for (var key in obj) {64 self.locals[key] = obj[key];65 }66 return self;67 };6869 // expose objects to each other70 this.use(function(req, res, next){71 var charset;72 res.setHeader('X-Powered-By', 'Express');73 req.app = res.app = self;74 req.res = res;75 res.req = req;76 req.next = next;7778 // charset79 if (charset = self.set('charset')) res.charset = charset;8081 /**82 * Assign several locals with the given `obj`,83 * or return the locals.84 *85 * @param {Object} obj86 * @return {Object|ServerResponse}87 * @api public88 */8990 res.locals = function(obj){91 for (var key in obj) {92 res.locals[key] = obj[key];93 }94 return res;95 };9697 next();98 });99100 // apply middleware101 if (middleware) middleware.forEach(self.use.bind(self));102103 // router104 this.routes = new Router(this);105 this.__defineGetter__('router', function(){106 this.__usedRouter = true;107 return self.routes.middleware;108 });109110 // default locals111 this.locals.settings = this.settings;112113 // default production configuration114 this.configure('production', function(){115 this.enable('view cache');116 });117118 // route manipulation methods119 methods.forEach(function(method){120 self.lookup[method] = function(path){121 return self.routes.lookup(method, path);122 };123124 self.match[method] = function(path){125 return self.routes.match(method, path);126 };127128 self.remove[method] = function(path){129 return self.routes.lookup(method, path).remove();130 };131 });132133 // del -> delete134 self.lookup.del = self.lookup.delete;135 self.match.del = self.match.delete;136 self.remove.del = self.remove.delete;137};138139/**140 * Remove routes matching the given `path`.141 *142 * @param {Route} path143 * @return {Boolean}144 * @api public145 */146147app.remove = function(path){148 return this.routes.lookup('all', path).remove();149};150151/**152 * Lookup routes defined with a path153 * equivalent to `path`.154 *155 * @param {Stirng} path156 * @return {Array}157 * @api public158 */159160app.lookup = function(path){161 return this.routes.lookup('all', path);162};163164/**165 * Lookup routes matching the given `url`.166 *167 * @param {Stirng} url168 * @return {Array}169 * @api public170 */171172app.match = function(url){173 return this.routes.match('all', url);174};175176/**177 * Proxy `connect.HTTPServer#use()` to apply settings to178 * mounted applications.179 *180 * @param {String|Function|Server} route181 * @param {Function|Server} middleware182 * @return {Server} for chaining183 * @api public184 */185186app.use = function(route, middleware){187 var app, home, handle;188189 if ('string' != typeof route) {190 middleware = route, route = '/';191 }192193 // express app194 if (middleware.handle && middleware.set) app = middleware;195196 // restore .app property on req and res197 if (app) {198 app.route = route;199 middleware = function(req, res, next) {200 var orig = req.app;201 app.handle(req, res, function(err){202 req.app = res.app = orig;203 next(err);204 });205 };206 }207208 connect.proto.use.call(this, route, middleware);209210 // mounted an app, invoke the hook211 // and adjust some settings212 if (app) {213 base = this.set('basepath') || this.route;214 if ('/' == base) base = '';215 base = base + (app.set('basepath') || app.route);216 app.set('basepath', base);217 app.parent = this;218 if (app.__mounted) app.__mounted.call(app, this);219 }220221 return this;222};223224/**225 * Assign a callback `fn` which is called226 * when this `Server` is passed to `Server#use()`.227 *228 * Examples:229 *230 * var app = express.createServer()231 * , blog = express.createServer();232 *233 * blog.mounted(function(parent){234 * // parent is app235 * // "this" is blog236 * });237 *238 * app.use(blog);239 *240 * @param {Function} fn241 * @return {Server} for chaining242 * @api public243 */244245app.mounted = function(fn){246 this.__mounted = fn;247 return this;248};249250/**251 * Register the given template engine callback `fn`252 * as `ext`. For example we may wish to map ".html"253 * files to ejs rather than using the ".ejs" extension.254 *255 * app.register('.html', require('ejs').render);256 *257 * or258 *259 * app.register('html', require('ejs').render);260 *261 * @param {String} ext262 * @param {Function} fn263 * @return {Server} for chaining264 * @api public265 */266267app.register = function(ext, fn){268 if ('.' != ext[0]) ext = '.' + ext;269 this.engines[ext] = fn;270 return this;271};272273/**274 * Map the given param placeholder `name`(s) to the given callback `fn`.275 * Register the given view helpers `obj`. This method276 * can be called several times to apply additional helpers.277 *278 * @param {Object} obj279 * @return {Server} for chaining280 * @api public281 */282283app.locals = function(obj){284 utils.merge(this._locals, obj);285 return this;286};287288/**289 * Map the given param placeholder `name`(s) to the given callback(s).290 *291 * Param mapping is used to provide pre-conditions to routes292 * which us normalized placeholders. This callback has the same293 * signature as regular middleware, for example below when ":userId"294 * is used this function will be invoked in an attempt to load the user.295 *296 * app.param('userId', function(req, res, next, id){297 * User.find(id, function(err, user){298 * if (err) {299 * next(err);300 * } else if (user) {301 * req.user = user;302 * next();303 * } else {304 * next(new Error('failed to load user'));305 * }306 * });307 * });308 *309 * Passing a single function allows you to map logic310 * to the values passed to `app.param()`, for example311 * this is useful to provide coercion support in a concise manner.312 *313 * The following example maps regular expressions to param values314 * ensuring that they match, otherwise passing control to the next315 * route:316 *317 * app.param(function(name, regexp){318 * if (regexp instanceof RegExp) {319 * return function(req, res, next, val){320 * var captures;321 * if (captures = regexp.exec(String(val))) {322 * req.params[name] = captures;323 * next();324 * } else {325 * next('route');326 * }327 * }328 * }329 * });330 *331 * We can now use it as shown below, where "/commit/:commit" expects332 * that the value for ":commit" is at 5 or more digits. The capture333 * groups are then available as `req.params.commit` as we defined334 * in the function above.335 *336 * app.param('commit', /^\d{5,}$/);337 *338 * For more of this useful functionality take a look339 * at [express-params](http://github.com/visionmedia/express-params).340 *341 * @param {String|Array|Function} name342 * @param {Function} fn343 * @return {Server} for chaining344 * @api public345 */346347app.param = function(name, fn){348 var self = this349 , fns = [].slice.call(arguments, 1);350351 // array352 if (Array.isArray(name)) {353 name.forEach(function(name){354 fns.forEach(function(fn){355 self.param(name, fn);356 });357 });358 // param logic359 } else if ('function' == typeof name) {360 this.routes.param(name);361 // single362 } else {363 if (':' == name[0]) name = name.substr(1);364 fns.forEach(function(fn){365 self.routes.param(name, fn);366 });367 }368369 return this;370};371372/**373 * Register the given callback `fn` for the given `type`.374 *375 * @param {String} type376 * @param {Function} fn377 * @return {Server} for chaining378 * @api public379 */380381app.is = function(type, fn){382 if (!fn) return this.isCallbacks[type];383 this.isCallbacks[type] = fn;384 return this;385};386387/**388 * Assign `setting` to `val`, or return `setting`'s value.389 * Mounted servers inherit their parent server's settings.390 *391 * @param {String} setting392 * @param {String} val393 * @return {Server|Mixed} for chaining, or the setting value394 * @api public395 */396397app.set = function(setting, val){398 if (val === undefined) {399 if (this.settings.hasOwnProperty(setting)) {400 return this.settings[setting];401 } else if (this.parent) {402 return this.parent.set(setting);403 }404 } else {405 this.settings[setting] = val;406 return this;407 }408};409410/**411 * Check if `setting` is enabled.412 *413 * @param {String} setting414 * @return {Boolean}415 * @api public416 */417418app.enabled = function(setting){419 return !!this.set(setting);420};421422/**423 * Check if `setting` is disabled.424 *425 * @param {String} setting426 * @return {Boolean}427 * @api public428 */429430app.disabled = function(setting){431 return !this.set(setting);432};433434/**435 * Enable `setting`.436 *437 * @param {String} setting438 * @return {Server} for chaining439 * @api public440 */441442app.enable = function(setting){443 return this.set(setting, true);444};445446/**447 * Disable `setting`.448 *449 * @param {String} setting450 * @return {Server} for chaining451 * @api public452 */453454app.disable = function(setting){455 return this.set(setting, false);456};457458/**459 * Redirect `key` to `url`.460 *461 * @param {String} key462 * @param {String} url463 * @return {Server} for chaining464 * @api public465 */466467app.redirect = function(key, url){468 this.redirects[key] = url;469 return this;470};471472/**473 * Configure callback for zero or more envs,474 * when no env is specified that callback will475 * be invoked for all environments. Any combination476 * can be used multiple times, in any order desired.477 *478 * Examples:479 *480 * app.configure(function(){481 * // executed for all envs482 * });483 *484 * app.configure('stage', function(){485 * // executed staging env486 * });487 *488 * app.configure('stage', 'production', function(){489 * // executed for stage and production490 * });491 *492 * @param {String} env...493 * @param {Function} fn494 * @return {Server} for chaining495 * @api public496 */497498app.configure = function(env, fn){499 var envs = 'all'500 , args = toArray(arguments);501 fn = args.pop();502 if (args.length) envs = args;503 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);504 return this;505};506507/**508 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.509 */510511methods.forEach(function(method){512 app[method] = function(path){513 if (1 == arguments.length) return this.routes.lookup(method, path);514 var args = [method].concat(toArray(arguments));515 if (!this.__usedRouter) this.use(this.router);516 return this.routes._route.apply(this.routes, args);517 }518});519520/**521 * Special-cased "all" method, applying the given route `path`,522 * middleware, and callback to _every_ HTTP method.523 *524 * @param {String} path525 * @param {Function} ...526 * @return {Server} for chaining527 * @api public528 */529530app.all = function(path){531 var args = arguments;532 if (1 == args.length) return this.routes.lookup('all', path);533 methods.forEach(function(method){534 if ('all' == method) return;535 app[method].apply(this, args);536 }, this);537 return this;538};539540// del -> delete alias541542app.del = app.delete;543544/**545 * Render the given `view` name with `options`546 * and a callback accepting an error and the547 * rendered template string.548 *549 * @param {String} view550 * @param {String|Function} options or fn551 * @param {Function} fn552 * @api public553 */554555app.render = function(view, options, fn){556 var self = this557 , opts = {}558 , engines = this.engines;559560 // support callback function as second arg561 if ('function' == typeof options) {562 fn = options, options = {};563 }564565 // merge app.locals566 utils.merge(opts, this.locals);567568 // merge options.locals569 if (options.locals) {570 utils.merge(opts, options.locals);571 delete opts.locals;572 }573574 // merge options575 utils.merge(opts, options);576577 // join "view engine" if necessary578 var ext = extname(view);579 if (!ext) view += '.' + (ext = this.set('view engine'));580581 // pass .cache to the engine582 opts.cache = this.enabled('view cache');583584 // when no extension nor "view engine" is given585 if (!ext) return fn(new Error('failed to find view "' + view + '"'));586587 // render588 try {589 var engine = engines[ext] = engines[ext] || require(ext);590 this.lookup(view, function(err, path){591 if (err) return fn(err);592 opts.filename = path;593 view = fs.readFileSync(path, 'utf8');594 engine.render(view, opts, fn);595 });596 } catch (err) {597 fn(err);598 }599};600601/**602 * Lookup the given `view` and callback `fn(err, path)`.603 *604 * @param {String} view605 * @param {String} fn606 * @api public607 */608609app.lookup = function(view, fn){610 var root = this.set('views') || process.cwd() + '/views';611 fn(null, join(root, view));612};