application.js
This file
Path
lib/application.js
594 lines · 12.8 KiB · JavaScript
Last changed by
request-level render()Tj Holowaychukbefore adoptionc40c54f
History of this fileTake it
application.jsTj Holowaychukbefore adoptiond0585bd
lines 1–41why, one step back12/*!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 , union = require('./utils').union18 , url = require('url')19 , utils = connect.utils20 , path = require('path')21 , extname = path.extname22 , join = path.join23 , fs = require('fs')24 , qs = require('qs');2526/**27 * Expose `HTTPServer`.28 */2930var app = exports = module.exports = {};3132/**33 * Initialize the server.34 *35 * @param {Array} middleware36 * @api private37 */3839app.init = function(middleware){40 var self = this;41 this.settings = {};added app.register()Tj Holowaychukbefore adoptiona9396ef
line 42why, one step back42 this.engines = {};application.jsTj Holowaychukbefore adoptiond0585bd
lines 43–253why, one step back43 this.redirects = {};44 this.isCallbacks = {};4546 this.set('home', '/');47 this.set('env', process.env.NODE_ENV || 'development');48 this.use(connect.query());4950 /**51 * Assign several locals with the given `obj`,52 * or return the locals.53 *54 * @param {Object} obj55 * @return {Object|HTTPServer}56 * @api public57 */5859 this.locals = function(obj){60 for (var key in obj) {61 self.locals[key] = obj[key];62 }63 return self;64 };6566 // expose objects to each other67 this.use(function(req, res, next){68 var charset;69 req.query = req.query || {};70 res.setHeader('X-Powered-By', 'Express');71 req.app = res.app = self;72 req.res = res;73 res.req = req;74 req.next = next;7576 // charset77 if (charset = self.set('charset')) res.charset = charset;7879 /**80 * Assign several locals with the given `obj`,81 * or return the locals.82 *83 * @param {Object} obj84 * @return {Object|ServerResponse}85 * @api public86 */8788 res.locals = function(obj){89 for (var key in obj) {90 res.locals[key] = obj[key];91 }92 return res;93 };9495 next();96 });9798 // apply middleware99 if (middleware) middleware.forEach(self.use.bind(self));100101 // router102 this.routes = new Router(this);103 this.__defineGetter__('router', function(){104 this.__usedRouter = true;105 return self.routes.middleware;106 });107108 // default locals109 this.locals.settings = this.settings;110111 // default development configuration112 this.configure('development', function(){113 this.enable('hints');114 });115116 // default production configuration117 this.configure('production', function(){118 this.enable('view cache');119 });120121 // route manipulation methods122 methods.forEach(function(method){123 self.lookup[method] = function(path){124 return self.routes.lookup(method, path);125 };126127 self.match[method] = function(path){128 return self.routes.match(method, path);129 };130131 self.remove[method] = function(path){132 return self.routes.lookup(method, path).remove();133 };134 });135136 // del -> delete137 self.lookup.del = self.lookup.delete;138 self.match.del = self.match.delete;139 self.remove.del = self.remove.delete;140};141142/**143 * Remove routes matching the given `path`.144 *145 * @param {Route} path146 * @return {Boolean}147 * @api public148 */149150app.remove = function(path){151 return this.routes.lookup('all', path).remove();152};153154/**155 * Lookup routes defined with a path156 * equivalent to `path`.157 *158 * @param {Stirng} path159 * @return {Array}160 * @api public161 */162163app.lookup = function(path){164 return this.routes.lookup('all', path);165};166167/**168 * Lookup routes matching the given `url`.169 *170 * @param {Stirng} url171 * @return {Array}172 * @api public173 */174175app.match = function(url){176 return this.routes.match('all', url);177};178179/**180 * Proxy `connect.HTTPServer#use()` to apply settings to181 * mounted applications.182 *183 * @param {String|Function|Server} route184 * @param {Function|Server} middleware185 * @return {Server} for chaining186 * @api public187 */188189app.use = function(route, middleware){190 var app, home, handle;191192 if ('string' != typeof route) {193 middleware = route, route = '/';194 }195196 // express app197 if (middleware.handle && middleware.set) app = middleware;198199 // restore .app property on req and res200 if (app) {201 app.route = route;202 middleware = function(req, res, next) {203 var orig = req.app;204 app.handle(req, res, function(err){205 req.app = res.app = orig;206 next(err);207 });208 };209 }210211 connect.proto.use.call(this, route, middleware);212213 // mounted an app, invoke the hook214 // and adjust some settings215 if (app) {216 base = this.set('basepath') || this.route;217 if ('/' == base) base = '';218 base = base + (app.set('basepath') || app.route);219 app.set('basepath', base);220 app.parent = this;221 if (app.__mounted) app.__mounted.call(app, this);222 }223224 return this;225};226227/**228 * Assign a callback `fn` which is called229 * when this `Server` is passed to `Server#use()`.230 *231 * Examples:232 *233 * var app = express.createServer()234 * , blog = express.createServer();235 *236 * blog.mounted(function(parent){237 * // parent is app238 * // "this" is blog239 * });240 *241 * app.use(blog);242 *243 * @param {Function} fn244 * @return {Server} for chaining245 * @api public246 */247248app.mounted = function(fn){249 this.__mounted = fn;250 return this;251};252253/**added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 254–256why, one step back254 * Register the given template engine callback `fn`255 * as `ext`. For example we may wish to map ".html"256 * files to ejs rather than using the ".ejs" extension.application.jsTj Holowaychukbefore adoptiond0585bd
line 257why, one step back257 *added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 258–265why, one step back258 * app.register('.html', require('ejs').render);259 *260 * or261 *262 * app.register('html', require('ejs').render);263 *264 * @param {String} ext265 * @param {Function} fnapplication.jsTj Holowaychukbefore adoptiond0585bd
lines 266–269why, one step back266 * @return {Server} for chaining267 * @api public268 */269added app.register()Tj Holowaychukbefore adoptiona9396ef
lines 270–272why, one step back270app.register = function(ext, fn){271 if ('.' != ext[0]) ext = '.' + ext;272 this.engines[ext] = fn;application.jsTj Holowaychukbefore adoptiond0585bd
lines 273–586why, one step back273 return this;274};275276/**277 * Map the given param placeholder `name`(s) to the given callback `fn`.278 * Register the given view helpers `obj`. This method279 * can be called several times to apply additional helpers.280 *281 * @param {Object} obj282 * @return {Server} for chaining283 * @api public284 */285286app.locals = function(obj){287 utils.merge(this._locals, obj);288 return this;289};290291/**292 * Map the given param placeholder `name`(s) to the given callback(s).293 *294 * Param mapping is used to provide pre-conditions to routes295 * which us normalized placeholders. This callback has the same296 * signature as regular middleware, for example below when ":userId"297 * is used this function will be invoked in an attempt to load the user.298 *299 * app.param('userId', function(req, res, next, id){300 * User.find(id, function(err, user){301 * if (err) {302 * next(err);303 * } else if (user) {304 * req.user = user;305 * next();306 * } else {307 * next(new Error('failed to load user'));308 * }309 * });310 * });311 *312 * Passing a single function allows you to map logic313 * to the values passed to `app.param()`, for example314 * this is useful to provide coercion support in a concise manner.315 *316 * The following example maps regular expressions to param values317 * ensuring that they match, otherwise passing control to the next318 * route:319 *320 * app.param(function(name, regexp){321 * if (regexp instanceof RegExp) {322 * return function(req, res, next, val){323 * var captures;324 * if (captures = regexp.exec(String(val))) {325 * req.params[name] = captures;326 * next();327 * } else {328 * next('route');329 * }330 * }331 * }332 * });333 *334 * We can now use it as shown below, where "/commit/:commit" expects335 * that the value for ":commit" is at 5 or more digits. The capture336 * groups are then available as `req.params.commit` as we defined337 * in the function above.338 *339 * app.param('commit', /^\d{5,}$/);340 *341 * For more of this useful functionality take a look342 * at [express-params](http://github.com/visionmedia/express-params).343 *344 * @param {String|Array|Function} name345 * @param {Function} fn346 * @return {Server} for chaining347 * @api public348 */349350app.param = function(name, fn){351 var self = this352 , fns = [].slice.call(arguments, 1);353354 // array355 if (Array.isArray(name)) {356 name.forEach(function(name){357 fns.forEach(function(fn){358 self.param(name, fn);359 });360 });361 // param logic362 } else if ('function' == typeof name) {363 this.routes.param(name);364 // single365 } else {366 if (':' == name[0]) name = name.substr(1);367 fns.forEach(function(fn){368 self.routes.param(name, fn);369 });370 }371372 return this;373};374375/**376 * Register the given callback `fn` for the given `type`.377 *378 * @param {String} type379 * @param {Function} fn380 * @return {Server} for chaining381 * @api public382 */383384app.is = function(type, fn){385 if (!fn) return this.isCallbacks[type];386 this.isCallbacks[type] = fn;387 return this;388};389390/**391 * Assign `setting` to `val`, or return `setting`'s value.392 * Mounted servers inherit their parent server's settings.393 *394 * @param {String} setting395 * @param {String} val396 * @return {Server|Mixed} for chaining, or the setting value397 * @api public398 */399400app.set = function(setting, val){401 if (val === undefined) {402 if (this.settings.hasOwnProperty(setting)) {403 return this.settings[setting];404 } else if (this.parent) {405 return this.parent.set(setting);406 }407 } else {408 this.settings[setting] = val;409 return this;410 }411};412413/**414 * Check if `setting` is enabled.415 *416 * @param {String} setting417 * @return {Boolean}418 * @api public419 */420421app.enabled = function(setting){422 return !!this.set(setting);423};424425/**426 * Check if `setting` is disabled.427 *428 * @param {String} setting429 * @return {Boolean}430 * @api public431 */432433app.disabled = function(setting){434 return !this.set(setting);435};436437/**438 * Enable `setting`.439 *440 * @param {String} setting441 * @return {Server} for chaining442 * @api public443 */444445app.enable = function(setting){446 return this.set(setting, true);447};448449/**450 * Disable `setting`.451 *452 * @param {String} setting453 * @return {Server} for chaining454 * @api public455 */456457app.disable = function(setting){458 return this.set(setting, false);459};460461/**462 * Redirect `key` to `url`.463 *464 * @param {String} key465 * @param {String} url466 * @return {Server} for chaining467 * @api public468 */469470app.redirect = function(key, url){471 this.redirects[key] = url;472 return this;473};474475/**476 * Configure callback for zero or more envs,477 * when no env is specified that callback will478 * be invoked for all environments. Any combination479 * can be used multiple times, in any order desired.480 *481 * Examples:482 *483 * app.configure(function(){484 * // executed for all envs485 * });486 *487 * app.configure('stage', function(){488 * // executed staging env489 * });490 *491 * app.configure('stage', 'production', function(){492 * // executed for stage and production493 * });494 *495 * @param {String} env...496 * @param {Function} fn497 * @return {Server} for chaining498 * @api public499 */500501app.configure = function(env, fn){502 var envs = 'all'503 , args = toArray(arguments);504 fn = args.pop();505 if (args.length) envs = args;506 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);507 return this;508};509510/**511 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.512 */513514methods.forEach(function(method){515 app[method] = function(path){516 if (1 == arguments.length) return this.routes.lookup(method, path);517 var args = [method].concat(toArray(arguments));518 if (!this.__usedRouter) this.use(this.router);519 return this.routes._route.apply(this.routes, args);520 }521});522523/**524 * Special-cased "all" method, applying the given route `path`,525 * middleware, and callback to _every_ HTTP method.526 *527 * @param {String} path528 * @param {Function} ...529 * @return {Server} for chaining530 * @api public531 */532533app.all = function(path){534 var args = arguments;535 if (1 == args.length) return this.routes.lookup('all', path);536 methods.forEach(function(method){537 if ('all' == method) return;538 app[method].apply(this, args);539 }, this);540 return this;541};542543// del -> delete alias544545app.del = app.delete;546547/**548 * Render the given `view` name with `opts`549 * and a callback accepting an error and the550 * rendered template string.551 *552 * @param {String} view553 * @param {String|Function} opts or fn554 * @param {Function} fn555 * @api public556 */557558app.render = function(view, opts, fn){559 var self = this560 , options = {}561 , engines = this.engines562 , root = this.set('views') || process.cwd() + '/views';563564 // support callback function as second arg565 if ('function' == typeof opts) {566 fn = opts, opts = null;567 }568569 // merge app.locals570 union(options, this.locals);571572 // merge render() options573 if (opts) utils.merge(options, opts);574575 // join "view engine" if necessary576 var ext = extname(view);577 if (!ext) view += '.' + (ext = this.set('view engine'));578579 // pass .cache to the engine580 options.cache = this.enabled('view cache');581582 // when no extension nor "view engine" is given583 if (!ext) return fn(new Error('failed to find view "' + view + '"'));584585 // render586 try {use app.engines instead of app.cacheTj Holowaychukbefore adoptione904132
line 587why, one step back587 var engine = engines[ext] = engines[ext] || require(ext);application.jsTj Holowaychukbefore adoptiond0585bd
lines 588–594why, one step back588 options.filename = join(root, view);589 view = fs.readFileSync(options.filename, 'utf8');590 engine.render(view, options, fn);591 } catch (err) {592 fn(err);593 }594};