Skip to content
Myr

request.js

This file

Path

lib/request.js

432 lines · 9.7 KiB · JavaScript

Last changed by

todoTJ Holowaychukbefore adoptionff9b82c

History of this file

Take it

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

new ViewTj Holowaychukbefore adoptione1da383

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')

new ViewTj Holowaychukbefore adoptione1da383

lines 15–16why, one step back
15 , parse = require('url').parse
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};

new ViewTj Holowaychukbefore adoptione1da383

lines 25–91why, one step back
25
26/**27 * Default notification formatters.28 */2930var defaultFormatters = exports.formatters = {31 s: String32 , d: function(val){ return val | 0; }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){

todoTJ Holowaychukbefore adoptionff9b82c

line 92why, one step back
92 // TODO: rename... add tests, make .get() .header()

new ViewTj Holowaychukbefore adoptione1da383

lines 93–100why, one step back
93 var val = this.header(field);
94 if (!val) return '';95 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');96 if (!regexp.exec(val)) return '';97 return RegExp.$1 || RegExp.$2;98};99100/**

docsTJ Holowaychukbefore adoptiona0d0ac6

line 101why, one step back
101 * Check if the given `type` is acceptable.

new ViewTj Holowaychukbefore adoptione1da383

lines 102–125why, one step back
102 *
103 * Examples:104 * 105 * // Accept: text/html106 * req.accepts('html');107 * // => true108 *109 * // Accept: text/*; application/json110 * req.accepts('html');111 * req.accepts('text/html');112 * req.accepts('text/plain');113 * req.accepts('application/json');114 * // => true115 *116 * req.accepts('image/png');117 * req.accepts('png');118 * // => false119 *120 * @param {String} type121 * @return {Boolean}122 * @api public123 */124125req.accepts = function(type){

Changed: req.accepts() utilizing utils.accepts()TJ Holowaychukbefore adoptionb605a5d

line 126why, one step back
126 return utils.accepts(type, this.header('Accept'));

new ViewTj Holowaychukbefore adoptione1da383

lines 127–129why, one step back
127};
128129/**

Added req.acceptedTJ Holowaychukbefore adoptiona8fd8cb

lines 130–155why, one step back
130 * Return an array of Accepted media types
131 * ordered from highest quality to lowest.132 *133 * Examples:134 *135 * [ { value: 'application/json',136 * quality: 1,137 * type: 'application',138 * subtype: 'json' },139 * { value: 'text/html',140 * quality: 0.5,141 * type: 'text',142 * subtype: 'html' } ]143 *144 * @return {Array}145 * @api public146 */147148req.__defineGetter__('accepted', function(){149 var accept = this.header('Accept');150 return accept151 ? utils.parseAccept(accept)152 : [];153});154155/**

Added req.acceptedLanguagesTJ Holowaychukbefore adoptione8c3736

lines 156–179why, one step back
156 * Return an array of Accepted languages
157 * ordered from highest quality to lowest.158 *159 * Examples:160 *161 * Accept-Language: en;q=.5, en-us162 * ['en-us', 'en']163 *164 * @return {Array}165 * @api public166 */167168req.__defineGetter__('acceptedLanguages', function(){169 var accept = this.header('Accept-Language');170 return accept171 ? utils172 .parseQuality(accept)173 .map(function(obj){174 return obj.value;175 })176 : [];177});178179/**

Added req.acceptedCharsetsTJ Holowaychukbefore adoption499d3d6

lines 180–203why, one step back
180 * Return an array of Accepted charsets
181 * ordered from highest quality to lowest.182 *183 * Examples:184 *185 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8186 * ['unicode-1-1', 'iso-8859-5']187 *188 * @return {Array}189 * @api public190 */191192req.__defineGetter__('acceptedCharsets', function(){193 var accept = this.header('Accept-Charset');194 return accept195 ? utils196 .parseQuality(accept)197 .map(function(obj){198 return obj.value;199 })200 : [];201});202203/**

new ViewTj Holowaychukbefore adoptione1da383

lines 204–373why, one step back
204 * Return the value of param `name` when present or `defaultValue`.
205 *206 * - Checks route placeholders, ex: _/user/:id_207 * - Checks query string params, ex: ?id=12208 * - Checks urlencoded body params, ex: id=12209 *210 * To utilize urlencoded request bodies, `req.body`211 * should be an object. This can be done by using212 * the `connect.bodyParser` middleware.213 *214 * @param {String} name215 * @param {Mixed} defaultValue216 * @return {String}217 * @api public218 */219220req.param = function(name, defaultValue){221 // route params like /user/:id222 if (this.params223 && this.params.hasOwnProperty(name)224 && undefined !== this.params[name]) {225 return this.params[name]; 226 }227 // query string params228 if (undefined !== this.query[name]) return this.query[name]; 229230 // request body params via connect.bodyParser231 if (this.body && undefined !== this.body[name]) return this.body[name];232233 return defaultValue;234};235236/**237 * Queue flash `msg` of the given `type`.238 *239 * This method is aliased as `req.notify()`.240 *241 * Examples:242 *243 * req.notify('info', 'email sent');244 * req.notify('info', 'email sent');245 * req.notify('error', 'email delivery failed');246 * req.notify('info', 'email re-sent');247 * // => 2248 *249 * req.notify('info');250 * // => ['email sent', 'email re-sent']251 *252 * req.notify('info');253 * // => []254 *255 * req.notify();256 * // => { error: ['email delivery failed'], info: [] }257 *258 * Formatting:259 *260 * Flash notifications also support arbitrary formatting support.261 * For example you may pass variable arguments to `req.notify()`262 * and use the %s specifier to be replaced by the associated argument:263 *264 * req.notify('info', 'email has been sent to %s.', userName);265 *266 * You may add addition formatters by defining `app.formatters`,267 * for example in the following snippet we define `%u` to uppercase268 * a string:269 *270 * app.formatters = {271 * u: function(val){272 * return String(val).toUpperCase();273 * }274 * };275 *276 * @param {String} type277 * @param {String} msg278 * @return {Array|Object|Number}279 * @api public280 */281282req.notify = function(type, msg){283 var sess = this.session;284 if (null == sess) throw Error('req.notify() requires sessions');285 var msgs = sess.notifications = sess.notifications || {};286287 switch (arguments.length) {288 // flush all messages289 case 0:290 sess.notifications = {};291 return msgs292 // flush messages for a specific type293 case 1:294 var arr = msgs[type];295 delete msgs[type];296 return arr || [];297 // set notification message298 default:299 var i = 2300 , args = arguments301 , formatters = this.app.formatters || {};302 formatters.__proto__ = defaultFormatters;303 msg = utils.miniMarkdown(msg);304 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){305 var formatter = formatters[format];306 if (formatter) return formatter(utils.escape(args[i++]));307 });308 return (msgs[type] = msgs[type] || []).push(msg);309 }310};311312/**313 * Check if the incoming request contains the "Content-Type" 314 * header field, and it contains the give mime `type`.315 *316 * Examples:317 *318 * // With Content-Type: text/html; charset=utf-8319 * req.is('html');320 * req.is('text/html');321 * // => true322 * 323 * // When Content-Type is application/json324 * req.is('json');325 * req.is('application/json');326 * // => true327 * 328 * req.is('html');329 * // => false330 * 331 * Ad-hoc callbacks can also be registered with Express, to perform332 * assertions again the request, for example if we need an expressive333 * way to check if our incoming request is an image, we can register "an image"334 * callback:335 * 336 * app.is('an image', function(req){337 * return 0 == req.headers['content-type'].indexOf('image');338 * });339 *340 * app.is('an attachment', function(req){341 * return 0 == req.headers['content-disposition'].indexOf('attachment');342 * });343 *344 * Now within our route callbacks, we can use to to assert content types345 * such as "image/jpeg", "image/png", etc.346 * 347 * app.post('/image/upload', function(req, res, next){348 * if (req.is('an image')) {349 * // do something350 * } else {351 * next();352 * }353 * });354 * 355 * @param {String} type356 * @return {Boolean}357 * @api public358 */359360req.is = function(type){361 var fn = this.app.is(type);362 if (fn) return fn(this);363 var contentType = this.headers['content-type'];364 if (!contentType) return;365 if (!~type.indexOf('/')) type = mime.lookup(type);366 if (~type.indexOf('*')) {367 type = type.split('/');368 contentType = contentType.split('/');369 if ('*' == type[0] && type[1] == contentType[1]) return true;370 if ('*' == type[1] && type[0] == contentType[0]) return true;371 }372 return !! ~contentType.indexOf(type);373};

move getters downTj Holowaychukbefore adoptiond6fabb6

lines 374–395why, one step back
374
375/**376 * Short-hand for `req.connection.encrypted`.377 *378 * @return {Boolean}379 * @api public380 */381382req.__defineGetter__('secure', function(){383 return req.connection.encrypted;384});385386/**387 * Short-hand for `require('url').parse(req.url).pathname`.388 *389 * @return {String}390 * @api public391 */392393req.__defineGetter__('path', function(){394 return parse(this.url).pathname;395});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 396–407why, one step back
396
397/**398 * Check if the request is fresh, aka399 * Last-Modified and/or the ETag400 * still match.401 *402 * @return {Boolean}403 * @api public404 */405406req.__defineGetter__('fresh', function(){407 return ! this.stale;

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 408why, one step back
408});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 409–420why, one step back
409
410/**411 * Check if the request is stale, aka412 * Last-Modified and/or the ETag for the413 * resource has changed.414 *415 * @return {Boolean}416 * @api public417 */418419req.__defineGetter__('stale', function(){420 return connect.utils.modified(this, this.res);

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 421why, one step back
421});

new ViewTj Holowaychukbefore adoptione1da383

lines 422–429why, one step back
422
423/**424 * Check if the request was an _XMLHttpRequest_.425 *426 * @return {Boolean}427 * @api public428 */429

Removed req.isXMLHttpRequestTj Holowaychukbefore adoptionaf46df7

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

case sensitivity testTj Holowaychukbefore adoption1a5636b

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

Removed req.isXMLHttpRequestTj Holowaychukbefore adoptionaf46df7

line 432why, one step back
432});