Skip to content
Myr

Merge branch 'indentation'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parents 5152823, 712771a · Browse files · 7 files+518 added−520 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+518 added−520 removed

  • other:+518 added−520 removed

7 files+518 added−520 removed

modified:docs/contrib.md+1 added-1 removed
modified:lib/express/index.js+1 added-1 removed
modified:lib/express/request.js+58 added-58 removed
7 unmodified lines
8/**9 * Module dependencies.10 */1112var http = require('http'),13 utils = require('./utils'),14 mime = require('connect/utils').mime;12var http = require('http')13 , utils = require('./utils')14 , mime = require('connect/utils').mime;1516/**17 * Default flash formatters.18 *19 * @type Object20 */2122var flashFormatters = exports.flashFormatters = {23 s: function(val){24 return String(val);25 }23 s: function(val){24 return String(val);25 }26};2728/**29 * Return request header or optional default.
18 unmodified lines
48 * @api public49 */5051http.IncomingMessage.prototype.header = function(name, defaultValue){52 return this.headers[name.toLowerCase()] || defaultValue;52 return this.headers[name.toLowerCase()] || defaultValue;53};5455/**56 * Check if the _Accept_ header is present, and includes the given `type`.
25 unmodified lines
82 * @api public83 */8485http.IncomingMessage.prototype.accepts = function(type){86 var accept = this.header('Accept');87 if (!accept || accept === '*/*') {88 return true;89 } else if (type) {90 // Allow "html" vs "text/html" etc91 if (type.indexOf('/') < 0) {92 type = mime.types['.' + type];93 }94 // Check if we have a direct match95 if (accept.indexOf(type) >= 0) {96 return true;97 // Check if we have type/*98 } else {99 type = type.split('/')[0] + '/*';100 return accept.indexOf(type) >= 0;101 }86 var accept = this.header('Accept');87 if (!accept || accept === '*/*') {88 return true;89 } else if (type) {90 // Allow "html" vs "text/html" etc91 if (type.indexOf('/') < 0) {92 type = mime.types['.' + type];93 }94 // Check if we have a direct match95 if (accept.indexOf(type) >= 0) {96 return true;97 // Check if we have type/*98 } else {103 return false;99 type = type.split('/')[0] + '/*';100 return accept.indexOf(type) >= 0;101 }102 } else {103 return false;104 }105};106107/**108 * Return the value of param `name` when present.
11 unmodified lines
120 * @api public121 */122123http.IncomingMessage.prototype.param = function(name){124 // Route params like /user/:id125 if (this.params[name] !== undefined) {126 return this.params[name]; 127 }128 // Query string params129 if (this.query[name] !== undefined) {130 return this.query[name]; 131 }132 // Request body params via connect.bodyDecoder133 if (this.body && this.body[name] !== undefined) {134 return this.body[name];135 }124 // Route params like /user/:id125 if (this.params[name] !== undefined) {126 return this.params[name]; 127 }128 // Query string params129 if (this.query[name] !== undefined) {130 return this.query[name]; 131 }132 // Request body params via connect.bodyDecoder133 if (this.body && this.body[name] !== undefined) {134 return this.body[name];135 }136};137138/**139 * Queue flash `msg` of the given `type`.
30 unmodified lines
170 * @api public171 */172173http.IncomingMessage.prototype.flash = function(type, msg){174 var msgs = this.session.flash = this.session.flash || {};175 if (type && msg) {176 var i = 2,177 args = arguments,178 formatters = this.app.flashFormatters || {};179 formatters.__proto__ = flashFormatters;180 msg = utils.miniMarkdown(utils.htmlEscape(msg));181 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){182 var formatter = formatters[format];183 if (formatter) return formatter(args[i++]);184 });185 return (msgs[type] = msgs[type] || []).push(msg);186 } else if (type) {187 var arr = msgs[type];188 delete msgs[type];189 return arr || [];190 } else {191 this.session.flash = {};192 return msgs;193 }174 var msgs = this.session.flash = this.session.flash || {};175 if (type && msg) {176 var i = 2177 , args = arguments178 , formatters = this.app.flashFormatters || {};179 formatters.__proto__ = flashFormatters;180 msg = utils.miniMarkdown(utils.htmlEscape(msg));181 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){182 var formatter = formatters[format];183 if (formatter) return formatter(args[i++]);184 });185 return (msgs[type] = msgs[type] || []).push(msg);186 } else if (type) {187 var arr = msgs[type];188 delete msgs[type];189 return arr || [];190 } else {191 this.session.flash = {};192 return msgs;193 }194};195196// Callback for isXMLHttpRequest / xhr197198function isxhr() {199 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';199 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';200}201202/**203 * Check if the request was an _XMLHttpRequest_.
2 unmodified lines
206 * @api public207 */208209http.IncomingMessage.prototype.__defineGetter__('isXMLHttpRequest', isxhr);210http.IncomingMessage.prototype.__defineGetter__('xhr', isxhr);210http.IncomingMessage.prototype.__defineGetter__('xhr', isxhr);
modified:lib/express/response.js+149 added-150 removed
7 unmodified lines
8/**9 * Module dependencies.10 */1112var fs = require('fs'),13 http = require('http'),14 path = require('path'),15 pump = require('sys').pump,16 utils = require('connect/utils'),17 mime = require('connect/utils').mime,18 parseRange = require('./utils').parseRange,19 Buffer = require('buffer').Buffer;12var fs = require('fs')13 , http = require('http')14 , path = require('path')15 , pump = require('sys').pump16 , utils = require('connect/utils')17 , mime = require('connect/utils').mime18 , parseRange = require('./utils').parseRange;1920/**21 * Header fields supporting multiple values.22 *
22 unmodified lines
45 * @api public46 */4748http.ServerResponse.prototype.send = function(body, headers, status){50 // Allow status as second arg51 if (typeof headers === 'number') {52 status = headers,53 headers = null;54 }49 // Allow status as second arg50 if (typeof headers === 'number') {51 status = headers,52 headers = null;53 }5456 // Defaults57 status = status || 200;55 // Defaults56 status = status || 200;5759 // Allow 0 args as 20460 if (!arguments.length) {61 body = status = 204;62 }58 // Allow 0 args as 20459 if (!arguments.length) {60 body = status = 204;61 }6264 // Determine content type65 switch (typeof body) {66 case 'number':67 if (!this.headers['Content-Type']) {68 this.contentType('.txt');69 }70 body = http.STATUS_CODES[status = body];71 break;72 case 'string':73 if (!this.headers['Content-Type']) {74 this.contentType('.html');75 }76 break;77 case 'object':78 if (body instanceof Buffer) {79 if (!this.headers['Content-Type']) {80 this.contentType('.bin');81 }82 } else {83 if (!this.headers['Content-Type']) {84 this.contentType('.json');85 }86 body = JSON.stringify(body);87 if (this.req.query.callback && this.app.settings['jsonp callback']) {88 body = this.req.query.callback + '(' + body + ');';89 }90 }91 break;92 }63 // Determine content type64 switch (typeof body) {65 case 'number':66 if (!this.headers['Content-Type']) {67 this.contentType('.txt');68 }69 body = http.STATUS_CODES[status = body];70 break;71 case 'string':72 if (!this.headers['Content-Type']) {73 this.contentType('.html');74 }75 break;76 case 'object':77 if (body instanceof Buffer) {78 if (!this.headers['Content-Type']) {79 this.contentType('.bin');80 }81 } else {82 if (!this.headers['Content-Type']) {83 this.contentType('.json');84 }85 body = JSON.stringify(body);86 if (this.req.query.callback && this.app.settings['jsonp callback']) {87 body = this.req.query.callback + '(' + body + ');';88 }89 }90 break;91 }9294 // Populate Content-Length95 if (!this.headers['Content-Length']) {96 this.header('Content-Length', body instanceof Buffer97 ? body.length98 : Buffer.byteLength(body));99 }93 // Populate Content-Length94 if (!this.headers['Content-Length']) {95 this.header('Content-Length', body instanceof Buffer96 ? body.length97 : Buffer.byteLength(body));98 }99101 // Merge headers passed102 if (headers) {103 var fields = Object.keys(headers);104 for (var i = 0, len = fields.length; i < len; ++i) {105 var field = fields[i];106 this.header(field, headers[field]);107 }100 // Merge headers passed101 if (headers) {102 var fields = Object.keys(headers);103 for (var i = 0, len = fields.length; i < len; ++i) {104 var field = fields[i];105 this.header(field, headers[field]);106 }107 }108110 // Strip irrelevant headers111 if (204 === status) {112 delete this.headers['Content-Type'];113 delete this.headers['Content-Length'];114 }109 // Strip irrelevant headers110 if (204 === status) {111 delete this.headers['Content-Type'];112 delete this.headers['Content-Length'];113 }114116 // Respond117 this.writeHead(status, this.headers);118 this.end('HEAD' == this.req.method ? undefined : body);115 // Respond116 this.writeHead(status, this.headers);117 this.end('HEAD' == this.req.method ? undefined : body);118};119120/**121 * Transfer the file at the given `path`. Automatically sets
11 unmodified lines
133 * @api public134 */135136http.ServerResponse.prototype.sendfile = function(path, fn){138 var self = this,139 streamThreshold = this.app.set('stream threshold') || 32 * 1024,140 ranges = self.req.headers.range;137 var self = this138 , streamThreshold = this.app.set('stream threshold') || 32 * 1024139 , ranges = self.req.headers.range;140142 if (~path.indexOf('..')) this.send(403);141 if (~path.indexOf('..')) this.send(403);142144 function error(err) {145 delete self.headers['Content-Disposition'];146 if (fn) {147 fn(err, path);148 } else {149 self.req.next(err);150 }143 function error(err) {144 delete self.headers['Content-Disposition'];145 if (fn) {146 fn(err, path);147 } else {148 self.req.next(err);149 }150 }151153 fs.stat(path, function(err, stat){152 fs.stat(path, function(err, stat){153 if (err) return error(err);154 if (stat.size >= streamThreshold) {155 var status = 200;156 if (ranges) ranges = parseRange(stat.size, ranges);157 if (ranges) {158 var stream = fs.createReadStream(path, ranges[0])159 , start = ranges[0].start160 , end = ranges[0].end;161 status = 206;162 self.header('Content-Range', 'bytes '163 + start164 + '-'165 + end166 + '/'167 + stat.size);168 self.header('Content-Length', end - start + 1);169 } else {170 var stream = fs.createReadStream(path);171 self.header('Content-Length', stat.size);172 }173 self.contentType(path);174 self.header('Accept-Ranges', 'bytes');175 self.writeHead(status, self.headers);176 pump(stream, self, function(err){177 fn && fn(err, path, true);178 });179 } else {180 fs.readFile(path, function(err, buf){181 if (err) return error(err);155 if (stat.size >= streamThreshold) {156 var status = 200;157 if (ranges) ranges = parseRange(stat.size, ranges);158 if (ranges) {159 var stream = fs.createReadStream(path, ranges[0]),160 start = ranges[0].start,161 end = ranges[0].end;162 status = 206;163 self.header('Content-Range', 'bytes '164 + start165 + '-'166 + end167 + '/'168 + stat.size);169 self.header('Content-Length', end - start + 1);170 } else {171 var stream = fs.createReadStream(path);172 self.header('Content-Length', stat.size);173 }174 self.contentType(path);175 self.header('Accept-Ranges', 'bytes');176 self.writeHead(status, self.headers);177 pump(stream, self, function(err){178 fn && fn(err, path, true);179 });180 } else {181 fs.readFile(path, function(err, buf){182 if (err) return error(err);183 self.contentType(path);184 self.send(buf);185 fn && fn(null, path);186 });187 }188 });182 self.contentType(path);183 self.send(buf);184 fn && fn(null, path);185 });186 }187 });188};189190/**191 * Set _Content-Type_ response header passed through `mime.type()`.
9 unmodified lines
201 * @api public202 */203204http.ServerResponse.prototype.contentType = function(type){206 return this.header('Content-Type', mime.type(type));205 return this.header('Content-Type', mime.type(type));206};207208/**209 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
3 unmodified lines
213 * @api public214 */215216http.ServerResponse.prototype.attachment = function(filename){218 this.header('Content-Disposition', filename219 ? 'attachment; filename="' + path.basename(filename) + '"'220 : 'attachment');221 return this;217 this.header('Content-Disposition', filename218 ? 'attachment; filename="' + path.basename(filename) + '"'219 : 'attachment');220 return this;221};222223/**224 * Transfer the file at the given `path`, with optional
7 unmodified lines
232 * @api public233 */234235http.ServerResponse.prototype.download = function(path, filename, fn){237 this.attachment(filename || path).sendfile(path, fn);236 this.attachment(filename || path).sendfile(path, fn);237};238239/**240 * Set or get response header `name` with optional `val`.
10 unmodified lines
251 * @api public252 */253254http.ServerResponse.prototype.header = function(name, val){256 if (val === undefined) {257 return this.headers[name];255 if (val === undefined) {256 return this.headers[name];257 } else {258 if (this.headers[name] && ~multiple.indexOf(name)) {259 return this.headers[name] += '\r\n' + name + ': ' + val;260 } else {259 if (this.headers[name] && ~multiple.indexOf(name)) {260 return this.headers[name] += '\r\n' + name + ': ' + val;261 } else {262 return this.headers[name] = val;261 return this.headers[name] = val;263 }262 }263 }264};265266/**267 * Clear cookie `name`.
2 unmodified lines
270 * @api public271 */272273http.ServerResponse.prototype.clearCookie = function(name){275 this.cookie(name, '', { expires: new Date(1) });274 this.cookie(name, '', { expires: new Date(1) });275};276277/**278 * Set cookie `name` to `val`.
9 unmodified lines
288 * @api public289 */290291http.ServerResponse.prototype.cookie = function(name, val, options){293 var cookie = utils.serializeCookie(name, val, options);294 this.header('Set-Cookie', cookie);292 var cookie = utils.serializeCookie(name, val, options);293 this.header('Set-Cookie', cookie);294};295296/**297 * Redirect to the given `url` with optional response `status`
36 unmodified lines
334 * @api public335 */336337http.ServerResponse.prototype.redirect = function(url, status){339 var basePath = this.app.set('home') || '/';338 var basePath = this.app.set('home') || '/';339341 // Setup redirect map342 var map = {343 back: this.req.headers.referrer || this.req.headers.referer || basePath,344 home: basePath345 };340 // Setup redirect map341 var map = {342 back: this.req.headers.referrer || this.req.headers.referer || basePath,343 home: basePath344 };345347 // Support custom redirect map348 map.__proto__ = this.app.redirects;346 // Support custom redirect map347 map.__proto__ = this.app.redirects;348350 // Attempt mapped redirect351 var mapped = typeof map[url] === 'function'352 ? map[url](this.req, this)353 : map[url];349 // Attempt mapped redirect350 var mapped = typeof map[url] === 'function'351 ? map[url](this.req, this)352 : map[url];353355 // Perform redirect356 url = mapped || url;354 // Perform redirect355 url = mapped || url;356358 // Respond359 this.send('Redirecting to ' + url, {360 'Content-Type': 'text/plain',361 'Location': url362 }, status || 302);357 // Respond358 this.send('Redirecting to ' + url, {359 'Content-Type': 'text/plain'360 , 'Location': url361 }, status || 302);362};
modified:lib/express/server.js+126 added-126 removed
7 unmodified lines
8/**9 * Module dependencies.10 */1112var url = require('url'),13 view = require('./view'),14 connect = require('connect'),15 utils = require('connect/utils'),16 queryString = require('querystring'),17 router = require('connect/middleware/router');12var url = require('url')13 , view = require('./view')14 , connect = require('connect')15 , utils = connect.utils16 , queryString = require('querystring')17 , router = require('connect/middleware/router');1819/**20 * Initialize a new `Server` with optional `middleware`.21 *
1 unmodified line
23 * @api public24 */2526var Server = exports = module.exports = function Server(middleware){27 var self = this;28 this.config = {};29 this.settings = {};30 this.redirects = {};31 this.viewHelpers = {};32 this.dynamicViewHelpers = {};33 this.errorHandlers = [];34 connect.Server.call(this, middleware || []);27 var self = this;28 this.config = {};29 this.settings = {};30 this.redirects = {};31 this.viewHelpers = {};32 this.dynamicViewHelpers = {};33 this.errorHandlers = [];34 connect.Server.call(this, middleware || []);3536 // Default "home" to / 37 this.set('home', '/');36 // Default "home" to / 37 this.set('home', '/');3839 // DEPRECATED: remove in 1.040 if (process.env.EXPRESS_ENV) {41 process.env.NODE_ENV = process.env.EXPRESS_ENV;42 console.warn('\x1b[33mWarning\x1b[0m: EXPRESS_ENV is deprecated, use NODE_ENV.');43 }39 // DEPRECATED: remove in 1.040 if (process.env.EXPRESS_ENV) {41 process.env.NODE_ENV = process.env.EXPRESS_ENV;42 console.warn('\x1b[33mWarning\x1b[0m: EXPRESS_ENV is deprecated, use NODE_ENV.');43 }4445 // Set "env" to NODE_ENV, defaulting to "development"46 this.set('env', process.env.NODE_ENV || 'development');45 // Set "env" to NODE_ENV, defaulting to "development"46 this.set('env', process.env.NODE_ENV || 'development');4748 // Expose objects to each other49 this.use(function(req, res, next){50 req.query = {};51 res.headers = {};52 req.app = res.app = self;53 req.res = res;54 res.req = req;55 req.next = next;56 // Assign req.params.get57 if (req.url.indexOf('?') > 0) {58 var query = url.parse(req.url).query;59 req.query = exports.parseQueryString(query);60 }61 next();62 });48 // Expose objects to each other49 this.use(function(req, res, next){50 req.query = {};51 res.headers = {};52 req.app = res.app = self;53 req.res = res;54 res.req = req;55 req.next = next;56 // Assign req.params.get57 if (req.url.indexOf('?') > 0) {58 var query = url.parse(req.url).query;59 req.query = exports.parseQueryString(query);60 }61 next();62 });6364 // Use router, expose as app.get(), etc65 var fn = router(function(app){ self.routes = app; });66 this.__defineGetter__('router', function(){67 this.__usedRouter = true;68 return fn;69 });64 // Use router, expose as app.get(), etc65 var fn = router(function(app){ self.routes = app; });66 this.__defineGetter__('router', function(){67 this.__usedRouter = true;68 return fn;69 });70};7172/**73 * Inherit from `connect.Server`.
11 unmodified lines
85 * Proxy in order to register error handlers.86 */8788Server.prototype.listen = function(){89 this.registerErrorHandlers();90 connect.Server.prototype.listen.apply(this, arguments);89 this.registerErrorHandlers();90 connect.Server.prototype.listen.apply(this, arguments);91};9293/**94 * Proxy in order to register error handlers.95 */9697Server.prototype.listenFD = function(){98 this.registerErrorHandlers();99 connect.Server.prototype.listenFD.apply(this, arguments);98 this.registerErrorHandlers();99 connect.Server.prototype.listenFD.apply(this, arguments);100};101102/**103 * Register error handlers. This is automatically
3 unmodified lines
107 * @api public108 */109110Server.prototype.registerErrorHandlers = function(){111 this.errorHandlers.forEach(function(fn){112 this.use(function(err, req, res, next){113 fn.apply(this, arguments);114 });115 }, this);116 return this;111 this.errorHandlers.forEach(function(fn){112 this.use(function(err, req, res, next){113 fn.apply(this, arguments);114 });115 }, this);116 return this;117};118119/**120 * Proxy `connect.Server#use()` to apply settings to
5 unmodified lines
126 * @api public127 */128129Server.prototype.use = function(route, middleware){130 if (typeof route !== 'string') {131 middleware = route, route = '/';132 }130 if (typeof route !== 'string') {131 middleware = route, route = '/';132 }133134 connect.Server.prototype.use.call(this, route, middleware);134 connect.Server.prototype.use.call(this, route, middleware);135136 // Mounted an app137 if (middleware instanceof Server) {138 // Home is /:route/:home139 var app = middleware,140 home = app.set('home');141 if (home === '/') home = '';142 app.set('home', (app.route || '') + home);143 app.parent = this;144 // Mounted hook145 if (app.__mounted) app.__mounted.call(app, this);146 }136 // Mounted an app137 if (middleware instanceof Server) {138 // Home is /:route/:home139 var app = middleware140 , home = app.set('home');141 if (home === '/') home = '';142 app.set('home', (app.route || '') + home);143 app.parent = this;144 // Mounted hook145 if (app.__mounted) app.__mounted.call(app, this);146 }147148 return this;148 return this;149};150151/**152 * Assign a callback `fn` which is called
16 unmodified lines
169 * @api public170 */171172Server.prototype.mounted = function(fn){173 this.__mounted = fn;174 return this;173 this.__mounted = fn;174 return this;175};176177/**178 * See: view.register.
2 unmodified lines
181 * @api public182 */183184Server.prototype.register = function(){185 view.register.apply(this, arguments);186 return this;185 view.register.apply(this, arguments);186 return this;187};188189/**190 * Register the given view helpers `obj`. This method
4 unmodified lines
195 * @api public196 */197198Server.prototype.helpers = function(obj){199 utils.merge(this.viewHelpers, obj);200 return this;199 utils.merge(this.viewHelpers, obj);200 return this;201};202203/**204 * Register the given dynamic view helpers `obj`. This method
4 unmodified lines
209 * @api public210 */211212Server.prototype.dynamicHelpers = function(obj){213 utils.merge(this.dynamicViewHelpers, obj);214 return this;213 utils.merge(this.dynamicViewHelpers, obj);214 return this;215};216217/**218 * Assign a custom exception handler callback `fn`.
4 unmodified lines
223 * @api public224 */225226Server.prototype.error = function(fn){227 this.errorHandlers.push(fn);228 return this;227 this.errorHandlers.push(fn);228 return this;229};230231/**232 * Assign `setting` to `val`, or return `setting`'s value.
5 unmodified lines
238 * @api public239 */240241Server.prototype.set = function(setting, val){242 if (val === undefined) {243 if (this.settings.hasOwnProperty(setting)) {244 return this.settings[setting];245 } else if (this.parent) {246 return this.parent.set(setting);247 }248 } else {249 this.settings[setting] = val;250 return this;242 if (val === undefined) {243 if (this.settings.hasOwnProperty(setting)) {244 return this.settings[setting];245 } else if (this.parent) {246 return this.parent.set(setting);247 }248 } else {249 this.settings[setting] = val;250 return this;251 }252};253254/**255 * Enable `setting`.
3 unmodified lines
259 * @api public260 */261262Server.prototype.enable = function(setting){263 return this.set(setting, true);263 return this.set(setting, true);264};265266/**267 * Disable `setting`.
3 unmodified lines
271 * @api public272 */273274Server.prototype.disable = function(setting){275 return this.set(setting, false);275 return this.set(setting, false);276};277278/**279 * Redirect `key` to `url`.
4 unmodified lines
284 * @api public285 */286287Server.prototype.redirect = function(key, url){288 this.redirects[key] = url;289 return this;288 this.redirects[key] = url;289 return this;290};291292/**293 * Configure callback for the given `env`.
4 unmodified lines
298 * @api public299 */300301Server.prototype.configure = function(env, fn){302 if (typeof env === 'function') {303 fn = env, env = 'all';304 }305 if (env === 'all' || this.set('env') === env) {306 fn.call(this);307 }308 return this;302 if (typeof env === 'function') {303 fn = env, env = 'all';304 }305 if (env === 'all' || this.set('env') === env) {306 fn.call(this);307 }308 return this;309};310311// Generate routing methods312313(function(method){314 Server.prototype[method] = function(path, fn){315 var self = this;314 Server.prototype[method] = function(path, fn){315 var self = this;316317 // Ensure router is mounted318 if (!this.__usedRouter) {319 this.use(this.router);320 }317 // Ensure router is mounted318 if (!this.__usedRouter) {319 this.use(this.router);320 }321322 // Route specific middleware support323 if (arguments.length > 2) {324 var args = Array.prototype.slice.call(arguments, 1);325 fn = args.pop();326 (function stack(middleware){327 middleware.forEach(function(fn){328 if (Array.isArray(fn)) {329 stack(fn);330 } else {331 self[method](path, fn);332 }333 });334 })(args);335 }322 // Route specific middleware support323 if (arguments.length > 2) {324 var args = Array.prototype.slice.call(arguments, 1);325 fn = args.pop();326 (function stack(middleware){327 middleware.forEach(function(fn){328 if (Array.isArray(fn)) {329 stack(fn);330 } else {331 self[method](path, fn);332 }333 });334 })(args);335 }336337 // Generate the route338 this.routes[method](path, fn);339 return this;340 };341 return arguments.callee;337 // Generate the route338 this.routes[method](path, fn);339 return this;340 };341 return arguments.callee;342})('get')('post')('put')('delete');343344// Alias delete as "del"345346Server.prototype.del = Server.prototype.delete;346Server.prototype.del = Server.prototype.delete;
modified:lib/express/utils.js+28 added-28 removed
modified:lib/express/view.js+155 added-156 removed
7 unmodified lines
8/**9 * Module dependencies.10 */1112var extname = require('path').extname,13 mime = require('connect/utils').mime,14 utils = require('connect/utils'),15 http = require('http'),16 fs = require('fs');12var extname = require('path').extname13 , utils = require('connect').utils14 , http = require('http')15 , fs = require('fs')16 , mime = utils.mime;1718/**19 * Cache supported template engine exports to20 * increase performance by lowering the number
20 unmodified lines
41 * @api private42 */4344function cacheViewSync(path) {45 return viewCache[path] = fs.readFileSync(path, 'utf8');45 return viewCache[path] = fs.readFileSync(path, 'utf8');46}4748/**49 * Return view root path for the given `app`.
3 unmodified lines
53 * @api private54 */5556function viewRoot(app) {57 return app.set('views') || process.cwd() + '/views';57 return app.set('views') || process.cwd() + '/views';58}5960/**61 * Register the given template engine `exports`
24 unmodified lines
86 * @api public87 */8889exports.register = function(ext, exports) {90 cache[ext] = exports;90 cache[ext] = exports;91};9293/**94 * Render `view` partial with the given `options`.
15 unmodified lines
110 * @api public111 */112113http.ServerResponse.prototype.partial = function(view, options, ext){114 // Inherit parent view extension when not present115 if (ext && view.indexOf('.') < 0) {116 view += ext;117 }114 // Inherit parent view extension when not present115 if (ext && view.indexOf('.') < 0) {116 view += ext;117 }118119 // Allow collection to be passed as second param120 if (options && options.hasOwnProperty('length')) {121 options = { collection: options };122 }119 // Allow collection to be passed as second param120 if (options && options.hasOwnProperty('length')) {121 options = { collection: options };122 }123124 // Defaults125 options = options || {};126 options.locals = options.locals || {};127 options.partial = true;128 options.layout = false;124 // Defaults125 options = options || {};126 options.locals = options.locals || {};127 options.partial = true;128 options.layout = false;129130 // Collection support131 var collection = options.collection;132 if (collection) {133 var name = options.as || view.split('.')[0],134 len = collection.length,135 buf = '';136 delete options.collection;137 options.locals.collectionLength = len;138 for (var i = 0, len = collection.length; i < len; ++i) {139 var val = collection[i];140 options.locals.firstInCollection = i === 0;141 options.locals.indexInCollection = i;142 options.locals.lastInCollection = i === len - 1;143 options.object = val;144 buf += this.partial(view, options);145 }146 return buf;147 } else {148 if (options.object) {149 var name = options.as || view.split('.')[0];150 if (typeof name === 'string') {151 options.locals[name] = options.object;152 } else if (name === global) {153 utils.merge(options.locals, options.object);154 } else {155 options.scope = options.object;156 }157 }158 return this.render(view, options);130 // Collection support131 var collection = options.collection;132 if (collection) {133 var name = options.as || view.split('.')[0]134 , len = collection.length135 , buf = '';136 delete options.collection;137 options.locals.collectionLength = len;138 for (var i = 0, len = collection.length; i < len; ++i) {139 var val = collection[i];140 options.locals.firstInCollection = i === 0;141 options.locals.indexInCollection = i;142 options.locals.lastInCollection = i === len - 1;143 options.object = val;144 buf += this.partial(view, options);145 }146 return buf;147 } else {148 if (options.object) {149 var name = options.as || view.split('.')[0];150 if (typeof name === 'string') {151 options.locals[name] = options.object;152 } else if (name === global) {153 utils.merge(options.locals, options.object);154 } else {155 options.scope = options.object;156 }157 }158 return this.render(view, options);159 }160};161162/**163 * Render `view` with the given `options` and optional callback `fn`.
17 unmodified lines
181 * @api public182 */183184http.ServerResponse.prototype.render = function(view, options, fn){185 // Support callback function as second arg186 if (typeof options === 'function') {187 fn = options, options = {};188 }189 190 var options = options || {},191 viewOptions = this.app.set('view options'),192 defaultEngine = this.app.set('view engine');185 // Support callback function as second arg186 if (typeof options === 'function') {187 fn = options, options = {};188 }189 190 var options = options || {}191 , app = this.app192 , viewOptions = app.settings['view options']193 , defaultEngine = app.settings['view engine'];194194 // Mixin "view options"195 if (viewOptions) options.__proto__ = viewOptions;195 // Mixin "view options"196 if (viewOptions) options.__proto__ = viewOptions;197197 // Support "view engine" setting198 if (view.indexOf('.') < 0 && defaultEngine) {199 view += '.' + defaultEngine;200 }198 // Support "view engine" setting199 if (view.indexOf('.') < 0 && defaultEngine) {200 view += '.' + defaultEngine;201 }202202 // Defaults203 var self = this,204 helpers = this.app.viewHelpers,205 dynamicHelpers = this.app.dynamicViewHelpers,206 root = viewRoot(this.app),207 ext = extname(view),208 partial = options.partial,209 layout = options.layout === undefined ? true : options.layout,210 layout = layout === true211 ? 'layout' + ext212 : layout;203 // Defaults204 var self = this205 , helpers = this.app.viewHelpers206 , dynamicHelpers = this.app.dynamicViewHelpers207 , root = viewRoot(this.app)208 , ext = extname(view)209 , partial = options.partial210 , layout = options.layout === undefined ? true : options.layout211 , layout = layout === true212 ? 'layout' + ext213 : layout;214214 // Allow layout name without extension215 if (typeof layout === 'string' && layout.indexOf('.') < 0) {216 layout += ext;217 }215 // Allow layout name without extension216 if (typeof layout === 'string' && layout.indexOf('.') < 0) {217 layout += ext;218 }219219 // Default execution scope to the response220 options.scope = options.scope || this.req;220 // Default execution scope to the response221 options.scope = options.scope || this.req;222222 // Auto-cache in production223 if (this.app.set('env') === 'production') {224 options.cache = true;225 }223 // Auto-cache in production224 if (this.app.set('env') === 'production') {225 options.cache = true;226 }227227 // Partials support228 if (options.partial) {229 root = this.app.set('partials')230 ? this.app.set('partials')231 : root + '/partials';232 }228 // Partials support229 if (options.partial) {230 root = app.settings.partials || root + '/partials';231 }232234 // View path235 var path = view[0] === '/'236 ? view237 : root + '/' + view;233 // View path234 var path = view[0] === '/'235 ? view236 : root + '/' + view;237239 // Pass filename to the engine and view240 options.locals = options.locals || {};241 options.locals.__filename = options.filename = path;238 // Pass filename to the engine and view239 options.locals = options.locals || {};240 options.locals.__filename = options.filename = path;241243 // Dynamic helper support244 if (options.dynamicHelpers !== false) {245 // cache246 if (!this.__dynamicHelpers) {247 this.__dynamicHelpers = {};248 var keys = Object.keys(dynamicHelpers);249 for (var i = 0, len = keys.length; i < len; ++i) {250 var key = keys[i],251 val = dynamicHelpers[key];252 if (typeof val === 'function') {253 this.__dynamicHelpers[key] = val.call(254 this.app, 255 this.req, 256 this);257 }258 }242 // Dynamic helper support243 if (options.dynamicHelpers !== false) {244 // cache245 if (!this.__dynamicHelpers) {246 this.__dynamicHelpers = {};247 var keys = Object.keys(dynamicHelpers);248 for (var i = 0, len = keys.length; i < len; ++i) {249 var key = keys[i]250 , val = dynamicHelpers[key];251 if (typeof val === 'function') {252 this.__dynamicHelpers[key] = val.call(253 this.app254 , this.req255 , this);256 }260261 // apply262 utils.merge(helpers, this.__dynamicHelpers);257 }258 }259260 // apply261 utils.merge(helpers, this.__dynamicHelpers);262 }263265 // Always expose partial() as a local266 options.locals.partial = function(view, options){267 return self.partial.call(self, view, options, ext);268 };264 // Always expose partial() as a local265 options.locals.partial = function(view, options){266 return self.partial.call(self, view, options, ext);267 };268 270 // Merge view helpers271 options.locals.__proto__ = helpers;269 // Merge view helpers270 options.locals.__proto__ = helpers;271273 function error(err) {274 if (fn) {275 fn(err);276 } else {277 self.req.next(err);278 }272 function error(err) {273 if (fn) {274 fn(err);275 } else {276 self.req.next(err);277 }278 }279281 // Cache contents282 try {283 var str = (options.cache ? viewCache[path] : null) || cacheViewSync(path);284 } catch (err) {285 return error(err);286 }280 // Cache contents281 try {282 var str = (options.cache ? viewCache[path] : null) || cacheViewSync(path);283 } catch (err) {284 return error(err);285 }286288 // Cache template engine exports289 var engine = cache[ext] || (cache[ext] = require(ext.substr(1)));287 // Cache template engine exports288 var engine = cache[ext] || (cache[ext] = require(ext.substr(1)));289291 // Attempt render292 try {293 var str = engine.render(str, options);294 } catch (err) {295 return error(err);296 }290 // Attempt render291 try {292 var str = engine.render(str, options);293 } catch (err) {294 return error(err);295 }296298 // Layout support299 if (layout) {300 options.layout = false;301 options.locals.body = str;302 options.isLayout = true;303 self.render(layout, options, fn);304 } else if (partial) {305 return str;306 } else if (fn) {307 fn(null, str);308 } else {309 this.send(str, options.headers, options.status);310 }297 // Layout support298 if (layout) {299 options.layout = false;300 options.locals.body = str;301 options.isLayout = true;302 self.render(layout, options, fn);303 } else if (partial) {304 return str;305 } else if (fn) {306 fn(null, str);307 } else {308 this.send(str, options.headers, options.status);309 }310};