Skip to content
Myr

application.js

This file

Path

lib/application.js

557 lines · 11.5 KiB · JavaScript

Last changed by

typoTj Holowaychukbefore adoptionc30c2f8

History of this file

Take it

The walk stopped after 200 commits: lines older than a751346 point at it.

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 1–14why, one step back
1
2/*!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')

refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba

line 15why, one step back
15 , middleware = require('./middleware')

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 16–19why, one step back
16 , View = require('./view')
17 , url = require('url')18 , utils = connect.utils19 , path = require('path')

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 20why, one step back
20 , http = require('http')

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 21–25why, one step back
21 , join = path.join
22 , fs = require('fs')23 , qs = require('qs');2425/**

typoTj Holowaychukbefore adoptionc30c2f8

line 26why, one step back
26 * Application prototype.

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 27–82why, one step back
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.isCallbacks = {};47 this.viewCallbacks = [];48 this.defaultConfiguration();4950 // route reflection methods51 methods.forEach(function(method){52 self.lookup[method] = function(path){53 return self._router.lookup(method, path);54 };5556 self.match[method] = function(path){57 return self._router.match(method, path);58 };5960 self.remove[method] = function(path){61 return self._router.lookup(method, path).remove();62 };63 });6465 // del -> delete66 self.lookup.del = self.lookup.delete;67 self.match.del = self.match.delete;68 self.remove.del = self.remove.delete;69};7071/**72 * Initialize application configuration.73 *74 * @api private75 */7677app.defaultConfiguration = function(){78 var self = this;7980 // default settings81 this.set('env', process.env.NODE_ENV || 'development');82

refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba

line 83why, one step back
83 // implicit middleware

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

line 84why, one step back
84 this.use(connect.query());

refactored init middleware into its own fileTj Holowaychukbefore adoption4c316ba

line 85why, one step back
85 this.use(middleware.init(this));

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

line 86why, one step back
86

docsTj Holowaychukbefore adoption6ae32fd

line 87why, one step back
87 // app locals

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 88–92why, one step back
88 this.locals = function(obj){
89 for (var key in obj) self.locals[key] = obj[key];90 return self;91 };92

docsTj Holowaychukbefore adoption6ae32fd

line 93why, one step back
93 // response locals

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 94–109why, one step back
94 this.locals.use = function(fn){
95 if (3 == fn.length) {96 self.viewCallbacks.push(fn);97 } else {98 self.viewCallbacks.push(function(req, res, done){99 fn(req, res);100 done();101 });102 }103 return this;104 };105106 // router107 this._router = new Router(this);108 this.routes = this._router.routes;109 this.__defineGetter__('router', function(){

fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284

line 110why, one step back
110 this._usedRouter = true;

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 111–160why, one step back
111 return self._router.middleware;
112 });113114 // default locals115 this.locals.settings = this.settings;116117 // default production configuration118 this.configure('production', function(){119 this.enable('view cache');120 });121};122123/**124 * Remove routes matching the given `path`.125 *126 * @param {Route} path127 * @return {Boolean}128 * @api public129 */130131app.remove = function(path){132 return this._router.lookup('all', path).remove();133};134135/**136 * Lookup routes defined with a path137 * equivalent to `path`.138 *139 * @param {Stirng} path140 * @return {Array}141 * @api public142 */143144app.lookup = function(path){145 return this._router.lookup('all', path);146};147148/**149 * Lookup routes matching the given `url`.150 *151 * @param {Stirng} url152 * @return {Array}153 * @api public154 */155156app.match = function(url){157 return this._router.match('all', url);158};159160/**

docsTj Holowaychukbefore adoption2e22887

line 161why, one step back
161 * Proxy `connect#use()` to apply settings to

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 162–164why, one step back
162 * mounted applications.
163 *164 * @param {String|Function|Server} route

misc refactoringTj Holowaychukbefore adoption1334a74

line 165why, one step back
165 * @param {Function|Server} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 166why, one step back
166 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 167–169why, one step back
167 * @api public
168 */169

misc refactoringTj Holowaychukbefore adoption1334a74

line 170why, one step back
170app.use = function(route, fn){

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 171–172why, one step back
171 var app, home, handle;
172

app.path()Tj Holowaychukbefore adoption17a831e

line 173why, one step back
173 // default route to '/'

misc refactoringTj Holowaychukbefore adoption1334a74

line 174why, one step back
174 if ('string' != typeof route) fn = route, route = '/';

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 175–176why, one step back
175
176 // express app

misc refactoringTj Holowaychukbefore adoption1334a74

line 177why, one step back
177 if (fn.handle && fn.set) app = fn;

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 178–181why, one step back
178
179 // restore .app property on req and res180 if (app) {181 app.route = route;

misc refactoringTj Holowaychukbefore adoption1334a74

line 182why, one step back
182 fn = function(req, res, next) {

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 183–190why, one step back
183 var orig = req.app;
184 app.handle(req, res, function(err){185 req.app = res.app = orig;186 next(err);187 });188 };189 }190

misc refactoringTj Holowaychukbefore adoption1334a74

line 191why, one step back
191 connect.proto.use.call(this, route, fn);

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

line 192why, one step back
192

removed "root" settingTj Holowaychukbefore adoption87b991c

line 193why, one step back
193 // mounted an app

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 194–195why, one step back
194 if (app) {
195 app.parent = this;

Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8

line 196why, one step back
196 app.emit('mount', this);

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 197–206why, one step back
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 *

Added app.engine() testsTj Holowaychukbefore adoption66f8ca5

line 207why, one step back
207 * app.engine('.html', require('ejs').render);

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 208–210why, one step back
208 *
209 * or210 *

Added app.engine() testsTj Holowaychukbefore adoption66f8ca5

line 211why, one step back
211 * app.engine('html', require('ejs').render);

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 212–214why, one step back
212 *
213 * @param {String} ext214 * @param {Function} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 215why, one step back
215 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 216–218why, one step back
216 * @api public
217 */218

Added app.engine() testsTj Holowaychukbefore adoption66f8ca5

line 219why, one step back
219app.engine = function(ext, fn){

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 220–279why, one step back
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} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 280why, one step back
280 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 281–313why, one step back
281 * @api public
282 */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} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 314why, one step back
314 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 315–344why, one step back
315 * @api public
316 */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 }

app.path()Tj Holowaychukbefore adoption17a831e

lines 345–359why, one step back
345};
346347/**348 * Return the app's absolute pathname349 * based on the parent(s) that have350 * mounted it.351 *352 * @return {String}353 * @api private354 */355356app.path = function(){357 return this.parent358 ? this.parent.path() + this.route359 : '';

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 360–389why, one step back
360};
361362/**363 * Check if `setting` is enabled.364 *365 * @param {String} setting366 * @return {Boolean}367 * @api public368 */369370app.enabled = function(setting){371 return !!this.set(setting);372};373374/**375 * Check if `setting` is disabled.376 *377 * @param {String} setting378 * @return {Boolean}379 * @api public380 */381382app.disabled = function(setting){383 return !this.set(setting);384};385386/**387 * Enable `setting`.388 *389 * @param {String} setting

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 390why, one step back
390 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 391–401why, one step back
391 * @api public
392 */393394app.enable = function(setting){395 return this.set(setting, true);396};397398/**399 * Disable `setting`.400 *401 * @param {String} setting

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 402why, one step back
402 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 403–431why, one step back
403 * @api public
404 */405406app.disable = function(setting){407 return this.set(setting, false);408};409410/**411 * Configure callback for zero or more envs,412 * when no env is specified that callback will413 * be invoked for all environments. Any combination414 * can be used multiple times, in any order desired.415 *416 * Examples:417 *418 * app.configure(function(){419 * // executed for all envs420 * });421 *422 * app.configure('stage', function(){423 * // executed staging env424 * });425 *426 * app.configure('stage', 'production', function(){427 * // executed for stage and production428 * });429 *430 * @param {String} env...431 * @param {Function} fn

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 432why, one step back
432 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 433–437why, one step back
433 * @api public
434 */435436app.configure = function(env, fn){437 var envs = 'all'

Removed toArray() utilTj Holowaychukbefore adoption7a7d77e

line 438why, one step back
438 , args = [].slice.call(arguments);

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 439–445why, one step back
439 fn = args.pop();
440 if (args.length) envs = args;441 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);442 return this;443};444445/**

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

lines 446–460why, one step back
446 * Listen for connections.
447 *448 * This method takes the same arguments449 * as node's `http.Server#listen()`. 450 *451 * @return {http.Server}452 * @api public453 */454455app.listen = function(){456 var server = http.createServer(this);457 return server.listen.apply(server, arguments);458};459460/**

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 461–466why, one step back
461 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.
462 */463464methods.forEach(function(method){465 app[method] = function(path){466 if ('get' == method && 1 == arguments.length) return this.set(path);

Removed toArray() utilTj Holowaychukbefore adoption7a7d77e

line 467why, one step back
467 var args = [method].concat([].slice.call(arguments));

fixed auto use(app.router)Tj Holowaychukbefore adoption92c5284

line 468why, one step back
468 if (!this._usedRouter) this.use(this.router);

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 469–478why, one step back
469 return this._router._route.apply(this._router, args);
470 }471});472473/**474 * Special-cased "all" method, applying the given route `path`,475 * middleware, and callback to _every_ HTTP method.476 *477 * @param {String} path478 * @param {Function} ...

Added app.listen() as a shortcut for http.createServer(app).listen()Tj Holowaychukbefore adoption9082e74

line 479why, one step back
479 * @return {app} for chaining

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 480–541why, one step back
480 * @api public
481 */482483app.all = function(path){484 var args = arguments;485 methods.forEach(function(method){486 if ('all' == method) return;487 app[method].apply(this, args);488 }, this);489 return this;490};491492// del -> delete alias493494app.del = app.delete;495496/**497 * Render the given view `name` name with `options`498 * and a callback accepting an error and the499 * rendered template string.500 *501 * @param {String} name502 * @param {String|Function} options or fn503 * @param {Function} fn504 * @api public505 */506507app.render = function(name, options, fn){508 var self = this509 , opts = {}510 , cache = this.cache511 , engines = this.engines512 , view;513514 // support callback function as second arg515 if ('function' == typeof options) {516 fn = options, options = {};517 }518519 // merge app.locals520 utils.merge(opts, this.locals);521522 // merge options.locals523 if (options.locals) {524 utils.merge(opts, options.locals);525 delete opts.locals;526 }527528 // merge options529 utils.merge(opts, options);530531 // set .cache unless explicitly provided532 opts.cache = null == opts.cache533 ? this.enabled('view cache')534 : opts.cache;535536 // primed cache537 if (opts.cache) view = cache[name];538539 // view540 if (!view) {541 view = new View(name, {

Fixed app.render() absolute path supportTj Holowaychukbefore adoptionb9dee73

lines 542–543why, one step back
542 defaultEngine: this.get('view engine')
543 , root: this.get('views') || process.cwd() + '/views'

port some express(1) stuff from 2.xTj Holowaychukbefore adoptiona751346

lines 544–557why, one step back
544 , engines: engines
545 });546547 // prime the cache548 if (opts.cache) cache[name] = view;549 }550551 // render552 try {553 view.render(opts, fn);554 } catch (err) {555 fn(err);556 }557};