application.js
This file
Path
lib/application.js
529 lines · 11.1 KiB · JavaScript
Last changed by
Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
History of this fileTake it
The walk stopped after 200 commits: lines older than 5b296b5 point at it.
middleware testsTj Holowaychukbefore adoption5b296b5
lines 1–13why, one step back1/*!2 * Express - proto3 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>4 * MIT Licensed5 */67/**8 * Module dependencies.9 */1011var connect = require('connect')12 , Router = require('./router')13 , methods = Router.methods.concat('del', 'all')refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 14why, one step back14 , middleware = require('./middleware')middleware testsTj Holowaychukbefore adoption5b296b5
lines 15–18why, one step back15 , View = require('./view')16 , url = require('url')17 , utils = connect.utils18 , path = require('path')Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 19why, one step back19 , http = require('http')middleware testsTj Holowaychukbefore adoption5b296b5
lines 20–24why, one step back20 , join = path.join21 , fs = require('fs')22 , qs = require('qs');2324/**typoTj Holowaychukbefore adoptionc30c2f8
line 25why, one step back25 * Application prototype.middleware testsTj Holowaychukbefore adoption5b296b5
lines 26–75why, one step back26 */2728var app = exports = module.exports = {};2930/**31 * Initialize the server.32 *33 * - setup default configuration34 * - setup default middleware35 * - setup route reflection methods36 *37 * @api private38 */3940app.init = function(){41 var self = this;42 this.cache = {};43 this.settings = {};44 this.engines = {};45 this.viewCallbacks = [];46 this.defaultConfiguration();4748 // route reflection methods49 methods.forEach(function(method){50 self.lookup[method] = function(path){51 return self._router.lookup(method, path);52 };5354 self.remove[method] = function(path){55 return self._router.lookup(method, path).remove();56 };57 });5859 // del -> delete60 self.lookup.del = self.lookup.delete;61 self.remove.del = self.remove.delete;62};6364/**65 * Initialize application configuration.66 *67 * @api private68 */6970app.defaultConfiguration = function(){71 var self = this;7273 // default settings74 this.set('env', process.env.NODE_ENV || 'development');75refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 76why, one step back76 // implicit middlewaremiddleware testsTj Holowaychukbefore adoption5b296b5
line 77why, one step back77 this.use(connect.query());refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba
line 78why, one step back78 this.use(middleware.init(this));middleware testsTj Holowaychukbefore adoption5b296b5
line 79why, one step back79docsTj Holowaychukbefore adoption6ae32fd
line 80why, one step back80 // app localsmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 81–85why, one step back81 this.locals = function(obj){82 for (var key in obj) self.locals[key] = obj[key];83 return self;84 };85docsTj Holowaychukbefore adoption6ae32fd
line 86why, one step back86 // response localsmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 87–102why, one step back87 this.locals.use = function(fn){88 if (3 == fn.length) {89 self.viewCallbacks.push(fn);90 } else {91 self.viewCallbacks.push(function(req, res, done){92 fn(req, res);93 done();94 });95 }96 return this;97 };9899 // router100 this._router = new Router(this);101 this.routes = this._router.routes;102 this.__defineGetter__('router', function(){fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284
line 103why, one step back103 this._usedRouter = true;Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
lines 104–106why, one step back104 this._router.caseSensitive = this.enabled('case sensitive routing');105 this._router.strict = this.enabled('strict routing');106 return this._router.middleware;middleware testsTj Holowaychukbefore adoption5b296b5
lines 107–111why, one step back107 });108109 // default locals110 this.locals.settings = this.settings;111Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
lines 112–116why, one step back112 // default configuration113 this.configure('development', function(){114 this.set('json spaces', 2);115 });116middleware testsTj Holowaychukbefore adoption5b296b5
lines 117–137why, one step back117 this.configure('production', function(){118 this.enable('view cache');119 });120};121122/**123 * Remove routes matching the given `path`.124 *125 * @param {Route} path126 * @return {Boolean}127 * @api public128 */129130app.remove = function(path){131 return this._router.lookup('all', path).remove();132};133134/**135 * Lookup routes defined with a path136 * equivalent to `path`.137 *Merge pull request #968 from peters/patch-1TJ Holowaychukbefore adoption4eb8bc0
line 138why, one step back138 * @param {String} pathmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 139–147why, one step back139 * @return {Array}140 * @api public141 */142143app.lookup = function(path){144 return this._router.lookup('all', path);145};146147/**docsTj Holowaychukbefore adoption2e22887
line 148why, one step back148 * Proxy `connect#use()` to apply settings tomiddleware testsTj Holowaychukbefore adoption5b296b5
lines 149–151why, one step back149 * mounted applications.150 *151 * @param {String|Function|Server} routemisc refactoringTj Holowaychukbefore adoption1334a74
line 152why, one step back152 * @param {Function|Server} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 153why, one step back153 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 154–156why, one step back154 * @api public155 */156misc refactoringTj Holowaychukbefore adoption1334a74
line 157why, one step back157app.use = function(route, fn){middleware testsTj Holowaychukbefore adoption5b296b5
lines 158–159why, one step back158 var app, home, handle;159app.path()Tj Holowaychukbefore adoption17a831e
line 160why, one step back160 // default route to '/'misc refactoringTj Holowaychukbefore adoption1334a74
line 161why, one step back161 if ('string' != typeof route) fn = route, route = '/';middleware testsTj Holowaychukbefore adoption5b296b5
lines 162–163why, one step back162163 // express appmisc refactoringTj Holowaychukbefore adoption1334a74
line 164why, one step back164 if (fn.handle && fn.set) app = fn;middleware testsTj Holowaychukbefore adoption5b296b5
lines 165–168why, one step back165166 // restore .app property on req and res167 if (app) {168 app.route = route;misc refactoringTj Holowaychukbefore adoption1334a74
line 169why, one step back169 fn = function(req, res, next) {middleware testsTj Holowaychukbefore adoption5b296b5
lines 170–177why, one step back170 var orig = req.app;171 app.handle(req, res, function(err){172 req.app = res.app = orig;173 next(err);174 });175 };176 }177misc refactoringTj Holowaychukbefore adoption1334a74
line 178why, one step back178 connect.proto.use.call(this, route, fn);middleware testsTj Holowaychukbefore adoption5b296b5
line 179why, one step back179removed "root" settingTj Holowaychukbefore adoption87b991c
line 180why, one step back180 // mounted an appmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 181–182why, one step back181 if (app) {182 app.parent = this;Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8
line 183why, one step back183 app.emit('mount', this);middleware testsTj Holowaychukbefore adoption5b296b5
lines 184–193why, one step back184 }185186 return this;187};188189/**190 * Register the given template engine callback `fn`191 * as `ext`. For example we may wish to map ".html"192 * files to ejs rather than using the ".ejs" extension.193 *Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 194why, one step back194 * app.engine('.html', require('ejs').render);middleware testsTj Holowaychukbefore adoption5b296b5
lines 195–197why, one step back195 *196 * or197 *Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 198why, one step back198 * app.engine('html', require('ejs').render);middleware testsTj Holowaychukbefore adoption5b296b5
lines 199–201why, one step back199 *200 * @param {String} ext201 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 202why, one step back202 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 203–205why, one step back203 * @api public204 */205Added app.engine() testsTj Holowaychukbefore adoption66f8ca5
line 206why, one step back206app.engine = function(ext, fn){middleware testsTj Holowaychukbefore adoption5b296b5
lines 207–266why, one step back207 if ('.' != ext[0]) ext = '.' + ext;208 this.engines[ext] = fn;209 return this;210};211212/**213 * Map the given param placeholder `name`(s) to the given callback(s).214 *215 * Param mapping is used to provide pre-conditions to routes216 * which us normalized placeholders. This callback has the same217 * signature as regular middleware, for example below when ":userId"218 * is used this function will be invoked in an attempt to load the user.219 *220 * app.param('userId', function(req, res, next, id){221 * User.find(id, function(err, user){222 * if (err) {223 * next(err);224 * } else if (user) {225 * req.user = user;226 * next();227 * } else {228 * next(new Error('failed to load user'));229 * }230 * });231 * });232 *233 * Passing a single function allows you to map logic234 * to the values passed to `app.param()`, for example235 * this is useful to provide coercion support in a concise manner.236 *237 * The following example maps regular expressions to param values238 * ensuring that they match, otherwise passing control to the next239 * route:240 *241 * app.param(function(name, regexp){242 * if (regexp instanceof RegExp) {243 * return function(req, res, next, val){244 * var captures;245 * if (captures = regexp.exec(String(val))) {246 * req.params[name] = captures;247 * next();248 * } else {249 * next('route');250 * }251 * }252 * }253 * });254 *255 * We can now use it as shown below, where "/commit/:commit" expects256 * that the value for ":commit" is at 5 or more digits. The capture257 * groups are then available as `req.params.commit` as we defined258 * in the function above.259 *260 * app.param('commit', /^\d{5,}$/);261 *262 * For more of this useful functionality take a look263 * at [express-params](http://github.com/visionmedia/express-params).264 *265 * @param {String|Array|Function} name266 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 267why, one step back267 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 268–306why, one step back268 * @api public269 */270271app.param = function(name, fn){272 var self = this273 , fns = [].slice.call(arguments, 1);274275 // array276 if (Array.isArray(name)) {277 name.forEach(function(name){278 fns.forEach(function(fn){279 self.param(name, fn);280 });281 });282 // param logic283 } else if ('function' == typeof name) {284 this._router.param(name);285 // single286 } else {287 if (':' == name[0]) name = name.substr(1);288 fns.forEach(function(fn){289 self._router.param(name, fn);290 });291 }292293 return this;294};295296/**297 * Assign `setting` to `val`, or return `setting`'s value.298 * Mounted servers inherit their parent server's settings.299 *300 * @param {String} setting301 * @param {String} val302 * @return {Server|Mixed} for chaining, or the setting value303 * @api public304 */305306app.set = function(setting, val){Fixed app.set() with undefinedTj Holowaychukbefore adoption7d24c2b
line 307why, one step back307 if (1 == arguments.length) {middleware testsTj Holowaychukbefore adoption5b296b5
lines 308–316why, one step back308 if (this.settings.hasOwnProperty(setting)) {309 return this.settings[setting];310 } else if (this.parent) {311 return this.parent.set(setting);312 }313 } else {314 this.settings[setting] = val;315 return this;316 }app.path()Tj Holowaychukbefore adoption17a831e
lines 317–331why, one step back317};318319/**320 * Return the app's absolute pathname321 * based on the parent(s) that have322 * mounted it.323 *324 * @return {String}325 * @api private326 */327328app.path = function(){329 return this.parent330 ? this.parent.path() + this.route331 : '';middleware testsTj Holowaychukbefore adoption5b296b5
lines 332–361why, one step back332};333334/**335 * Check if `setting` is enabled.336 *337 * @param {String} setting338 * @return {Boolean}339 * @api public340 */341342app.enabled = function(setting){343 return !!this.set(setting);344};345346/**347 * Check if `setting` is disabled.348 *349 * @param {String} setting350 * @return {Boolean}351 * @api public352 */353354app.disabled = function(setting){355 return !this.set(setting);356};357358/**359 * Enable `setting`.360 *361 * @param {String} settingAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 362why, one step back362 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 363–373why, one step back363 * @api public364 */365366app.enable = function(setting){367 return this.set(setting, true);368};369370/**371 * Disable `setting`.372 *373 * @param {String} settingAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 374why, one step back374 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 375–403why, one step back375 * @api public376 */377378app.disable = function(setting){379 return this.set(setting, false);380};381382/**383 * Configure callback for zero or more envs,384 * when no env is specified that callback will385 * be invoked for all environments. Any combination386 * can be used multiple times, in any order desired.387 *388 * Examples:389 *390 * app.configure(function(){391 * // executed for all envs392 * });393 *394 * app.configure('stage', function(){395 * // executed staging env396 * });397 *398 * app.configure('stage', 'production', function(){399 * // executed for stage and production400 * });401 *402 * @param {String} env...403 * @param {Function} fnAdded app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 404why, one step back404 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 405–409why, one step back405 * @api public406 */407408app.configure = function(env, fn){409 var envs = 'all'Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
line 410why, one step back410 , args = [].slice.call(arguments);middleware testsTj Holowaychukbefore adoption5b296b5
lines 411–417why, one step back411 fn = args.pop();412 if (args.length) envs = args;413 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);414 return this;415};416417/**Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
lines 418–432why, one step back418 * Listen for connections.419 *420 * This method takes the same arguments421 * as node's `http.Server#listen()`. 422 *423 * @return {http.Server}424 * @api public425 */426427app.listen = function(){428 var server = http.createServer(this);429 return server.listen.apply(server, arguments);430};431432/**middleware testsTj Holowaychukbefore adoption5b296b5
lines 433–438why, one step back433 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.434 */435436methods.forEach(function(method){437 app[method] = function(path){438 if ('get' == method && 1 == arguments.length) return this.set(path); Removed toArray() utilTj Holowaychukbefore adoption7a7d77e
line 439why, one step back439 var args = [method].concat([].slice.call(arguments));fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284
line 440why, one step back440 if (!this._usedRouter) this.use(this.router);Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9
line 441why, one step back441 return this._router.route.apply(this._router, args);middleware testsTj Holowaychukbefore adoption5b296b5
lines 442–450why, one step back442 }443});444445/**446 * Special-cased "all" method, applying the given route `path`,447 * middleware, and callback to _every_ HTTP method.448 *449 * @param {String} path450 * @param {Function} ...Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74
line 451why, one step back451 * @return {app} for chainingmiddleware testsTj Holowaychukbefore adoption5b296b5
lines 452–457why, one step back452 * @api public453 */454455app.all = function(path){456 var args = arguments;457 methods.forEach(function(method){backported fix from 2.x for app.all() del methodTj Holowaychukbefore adoptionc3c0fb9
line 458why, one step back458 if ('all' == method || 'del' == method) return;middleware testsTj Holowaychukbefore adoption5b296b5
lines 459–513why, one step back459 app[method].apply(this, args);460 }, this);461 return this;462};463464// del -> delete alias465466app.del = app.delete;467468/**469 * Render the given view `name` name with `options`470 * and a callback accepting an error and the471 * rendered template string.472 *473 * @param {String} name474 * @param {String|Function} options or fn475 * @param {Function} fn476 * @api public477 */478479app.render = function(name, options, fn){480 var self = this481 , opts = {}482 , cache = this.cache483 , engines = this.engines484 , view;485486 // support callback function as second arg487 if ('function' == typeof options) {488 fn = options, options = {};489 }490491 // merge app.locals492 utils.merge(opts, this.locals);493494 // merge options.locals495 if (options.locals) {496 utils.merge(opts, options.locals);497 delete opts.locals;498 }499500 // merge options501 utils.merge(opts, options);502503 // set .cache unless explicitly provided504 opts.cache = null == opts.cache505 ? this.enabled('view cache')506 : opts.cache;507508 // primed cache509 if (opts.cache) view = cache[name];510511 // view512 if (!view) {513 view = new View(name, {Fixed app.render() absolute path supportTj Holowaychukbefore adoptionb9dee73
lines 514–515why, one step back514 defaultEngine: this.get('view engine')515 , root: this.get('views') || process.cwd() + '/views'middleware testsTj Holowaychukbefore adoption5b296b5
lines 516–529why, one step back516 , engines: engines517 });518519 // prime the cache520 if (opts.cache) cache[name] = view;521 }522523 // render524 try {525 view.render(opts, fn);526 } catch (err) {527 fn(err);528 }529};