Skip to content
Myr

request.js

This file

Path

lib/request.js

379 lines · 9.0 KiB · JavaScript

Last changed by

no longer manipulate the req/res protos directlyTj Holowaychukbefore adoptiond249868

History of this file

Take it

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

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 1–13why, one step back
1
2/*!3 * Express - request4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var http = require('http')13 , utils = require('./utils')

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

line 14why, one step back
14 , connect = require('connect')

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

line 15why, one step back
15 , parse = require('url').parse

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

line 16why, one step back
16 , mime = require('mime');

no longer manipulate the req/res protos directlyTj Holowaychukbefore adoptiond249868

lines 17–24why, one step back
17
18/**19 * Request prototype.20 */2122var req = exports = module.exports = {23 __proto__: http.IncomingMessage.prototype24};

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 25–30why, one step back
25
26/**27 * Default notification formatters.28 */2930var defaultFormatters = exports.formatters = {

misc refactoringTj Holowaychukbefore adoption77d8823

lines 31–32why, one step back
31 s: String
32 , d: function(val){ return val | 0; }

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 33–97why, one step back
33};
3435/**36 * Return request header or optional default.37 *38 * The `Referrer` header field is special-cased,39 * both `Referrer` and `Referer` will yield are40 * interchangeable.41 *42 * Examples:43 *44 * req.header('Content-Type');45 * // => "text/plain"46 * 47 * req.header('content-type');48 * // => "text/plain"49 * 50 * req.header('Accept');51 * // => undefined52 * 53 * req.header('Accept', 'text/html');54 * // => "text/html"55 *56 * @param {String} name57 * @param {String} defaultValue58 * @return {String} 59 * @api public60 */6162req.header = function(name, defaultValue){63 switch (name = name.toLowerCase()) {64 case 'referer':65 case 'referrer':66 return this.headers.referrer67 || this.headers.referer68 || defaultValue;69 default:70 return this.headers[name] || defaultValue;71 }72};7374/**75 * Get `field`'s `param` value, defaulting to ''.76 *77 * Examples:78 *79 * req.get('content-disposition', 'filename');80 * // => "something.png"81 *82 * req.get('content-disposition', 'rawr');83 * // => ""84 *85 * @param {String} field86 * @param {String} param87 * @return {String}88 * @api public89 */9091req.get = function(field, param){92 var val = this.header(field);93 if (!val) return '';94 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');95 if (!regexp.exec(val)) return '';96 return RegExp.$1 || RegExp.$2;97};

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

lines 98–99why, one step back
98
99/**

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 100–249why, one step back
100 * Check if the _Accept_ header is present, and includes the given `type`.
101 *102 * When the _Accept_ header is not present `true` is returned. Otherwise103 * the given `type` is matched by an exact match, and then subtypes. You104 * may pass the subtype such as "html" which is then converted internally105 * to "text/html" using the mime lookup table.106 *107 * Examples:108 * 109 * // Accept: text/html110 * req.accepts('html');111 * // => true112 *113 * // Accept: text/*; application/json114 * req.accepts('html');115 * req.accepts('text/html');116 * req.accepts('text/plain');117 * req.accepts('application/json');118 * // => true119 *120 * req.accepts('image/png');121 * req.accepts('png');122 * // => false123 *124 * @param {String} type125 * @return {Boolean}126 * @api public127 */128129req.accepts = function(type){130 var accept = this.header('Accept')131 , type = String(type);132133 // when not present or "*/*" accept anything134 if (!accept || '*/*' == accept) return true;135136 // normalize extensions ".json" -> "json"137 if ('.' == type[0]) type = type.substr(1);138139 // allow "html" vs "text/html" etc140 if (!~type.indexOf('/')) type = mime.lookup(type);141142 // check if we have a direct match143 if (~accept.indexOf(type)) return true;144145 // check if we have type/*146 type = type.split('/')[0] + '/*';147 return !! ~accept.indexOf(type);148};149150/**151 * Return the value of param `name` when present or `defaultValue`.152 *153 * - Checks route placeholders, ex: _/user/:id_154 * - Checks query string params, ex: ?id=12155 * - Checks urlencoded body params, ex: id=12156 *157 * To utilize urlencoded request bodies, `req.body`158 * should be an object. This can be done by using159 * the `connect.bodyParser` middleware.160 *161 * @param {String} name162 * @param {Mixed} defaultValue163 * @return {String}164 * @api public165 */166167req.param = function(name, defaultValue){168 // route params like /user/:id169 if (this.params170 && this.params.hasOwnProperty(name)171 && undefined !== this.params[name]) {172 return this.params[name]; 173 }174 // query string params175 if (undefined !== this.query[name]) return this.query[name]; 176177 // request body params via connect.bodyParser178 if (this.body && undefined !== this.body[name]) return this.body[name];179180 return defaultValue;181};182183/**184 * Queue flash `msg` of the given `type`.185 *186 * This method is aliased as `req.notify()`.187 *188 * Examples:189 *190 * req.notify('info', 'email sent');191 * req.notify('info', 'email sent');192 * req.notify('error', 'email delivery failed');193 * req.notify('info', 'email re-sent');194 * // => 2195 *196 * req.notify('info');197 * // => ['email sent', 'email re-sent']198 *199 * req.notify('info');200 * // => []201 *202 * req.notify();203 * // => { error: ['email delivery failed'], info: [] }204 *205 * Formatting:206 *207 * Flash notifications also support arbitrary formatting support.208 * For example you may pass variable arguments to `req.notify()`209 * and use the %s specifier to be replaced by the associated argument:210 *211 * req.notify('info', 'email has been sent to %s.', userName);212 *213 * You may add addition formatters by defining `app.formatters`,214 * for example in the following snippet we define `%u` to uppercase215 * a string:216 *217 * app.formatters = {218 * u: function(val){219 * return String(val).toUpperCase();220 * }221 * };222 *223 * @param {String} type224 * @param {String} msg225 * @return {Array|Object|Number}226 * @api public227 */228229req.notify = function(type, msg){230 var sess = this.session;231 if (null == sess) throw Error('req.notify() requires sessions');232 var msgs = sess.notifications = sess.notifications || {};233234 switch (arguments.length) {235 // flush all messages236 case 0:237 sess.notifications = {};238 return msgs239 // flush messages for a specific type240 case 1:241 var arr = msgs[type];242 delete msgs[type];243 return arr || [];244 // set notification message245 default:246 var i = 2247 , args = arguments248 , formatters = this.app.formatters || {};249 formatters.__proto__ = defaultFormatters;

Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0

line 250why, one step back
250 msg = utils.miniMarkdown(msg);

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 251–252why, one step back
251 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
252 var formatter = formatters[format];

Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0

line 253why, one step back
253 if (formatter) return formatter(utils.escape(args[i++]));

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 254–320why, one step back
254 });
255 return (msgs[type] = msgs[type] || []).push(msg);256 }257};258259/**260 * Check if the incoming request contains the "Content-Type" 261 * header field, and it contains the give mime `type`.262 *263 * Examples:264 *265 * // With Content-Type: text/html; charset=utf-8266 * req.is('html');267 * req.is('text/html');268 * // => true269 * 270 * // When Content-Type is application/json271 * req.is('json');272 * req.is('application/json');273 * // => true274 * 275 * req.is('html');276 * // => false277 * 278 * Ad-hoc callbacks can also be registered with Express, to perform279 * assertions again the request, for example if we need an expressive280 * way to check if our incoming request is an image, we can register "an image"281 * callback:282 * 283 * app.is('an image', function(req){284 * return 0 == req.headers['content-type'].indexOf('image');285 * });286 *287 * app.is('an attachment', function(req){288 * return 0 == req.headers['content-disposition'].indexOf('attachment');289 * });290 *291 * Now within our route callbacks, we can use to to assert content types292 * such as "image/jpeg", "image/png", etc.293 * 294 * app.post('/image/upload', function(req, res, next){295 * if (req.is('an image')) {296 * // do something297 * } else {298 * next();299 * }300 * });301 * 302 * @param {String} type303 * @return {Boolean}304 * @api public305 */306307req.is = function(type){308 var fn = this.app.is(type);309 if (fn) return fn(this);310 var contentType = this.headers['content-type'];311 if (!contentType) return;312 if (!~type.indexOf('/')) type = mime.lookup(type);313 if (~type.indexOf('*')) {314 type = type.split('/');315 contentType = contentType.split('/');316 if ('*' == type[0] && type[1] == contentType[1]) return true;317 if ('*' == type[1] && type[0] == contentType[0]) return true;318 }319 return !! ~contentType.indexOf(type);320};

move getters downTj Holowaychukbefore adoptiond6fabb6

lines 321–342why, one step back
321
322/**323 * Short-hand for `req.connection.encrypted`.324 *325 * @return {Boolean}326 * @api public327 */328329req.__defineGetter__('secure', function(){330 return req.connection.encrypted;331});332333/**334 * Short-hand for `require('url').parse(req.url).pathname`.335 *336 * @return {String}337 * @api public338 */339340req.__defineGetter__('path', function(){341 return parse(this.url).pathname;342});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 343–354why, one step back
343
344/**345 * Check if the request is fresh, aka346 * Last-Modified and/or the ETag347 * still match.348 *349 * @return {Boolean}350 * @api public351 */352353req.__defineGetter__('fresh', function(){354 return ! this.stale;

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 355why, one step back
355});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 356–367why, one step back
356
357/**358 * Check if the request is stale, aka359 * Last-Modified and/or the ETag for the360 * resource has changed.361 *362 * @return {Boolean}363 * @api public364 */365366req.__defineGetter__('stale', function(){367 return connect.utils.modified(this, this.res);

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 368why, one step back
368});

use nextRoute() internallyTj Holowaychukbefore adoption34606c2

lines 369–376why, one step back
369
370/**371 * Check if the request was an _XMLHttpRequest_.372 *373 * @return {Boolean}374 * @api public375 */376

Removed req.isXMLHttpRequestTj Holowaychukbefore adoptionaf46df7

line 377why, one step back
377req.__defineGetter__('xhr', function(){

case sensitivity testTj Holowaychukbefore adoption1a5636b

line 378why, one step back
378 return 'xmlhttprequest' == this.header('X-Requested-With', '').toLowerCase();

Removed req.isXMLHttpRequestTj Holowaychukbefore adoptionaf46df7

line 379why, one step back
379});