Skip to content
Myr

request.js

This file

Path

lib/request.js

377 lines · 9.0 KiB · JavaScript

Last changed by

semicolonsTj Holowaychukbefore adoption1a1ed0a

History of this file

Take it

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

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 1–14why, 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 , req = http.IncomingMessage.prototype14 , utils = require('./utils')

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

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

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

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

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 17–23why, one step back
17 , mime = require('mime');
1819/**20 * Default notification formatters.21 */2223var defaultFormatters = exports.formatters = {

misc refactoringTj Holowaychukbefore adoption77d8823

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

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 26–90why, one step back
26};
2728/**29 * Return request header or optional default.30 *31 * The `Referrer` header field is special-cased,32 * both `Referrer` and `Referer` will yield are33 * interchangeable.34 *35 * Examples:36 *37 * req.header('Content-Type');38 * // => "text/plain"39 * 40 * req.header('content-type');41 * // => "text/plain"42 * 43 * req.header('Accept');44 * // => undefined45 * 46 * req.header('Accept', 'text/html');47 * // => "text/html"48 *49 * @param {String} name50 * @param {String} defaultValue51 * @return {String} 52 * @api public53 */5455req.header = function(name, defaultValue){56 switch (name = name.toLowerCase()) {57 case 'referer':58 case 'referrer':59 return this.headers.referrer60 || this.headers.referer61 || defaultValue;62 default:63 return this.headers[name] || defaultValue;64 }65};6667/**68 * Get `field`'s `param` value, defaulting to ''.69 *70 * Examples:71 *72 * req.get('content-disposition', 'filename');73 * // => "something.png"74 *75 * req.get('content-disposition', 'rawr');76 * // => ""77 *78 * @param {String} field79 * @param {String} param80 * @return {String}81 * @api public82 */8384req.get = function(field, param){85 var val = this.header(field);86 if (!val) return '';87 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');88 if (!regexp.exec(val)) return '';89 return RegExp.$1 || RegExp.$2;90};

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

lines 91–92why, one step back
91
92/**

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 93–122why, one step back
93 * Check if the _Accept_ header is present, and includes the given `type`.
94 *95 * When the _Accept_ header is not present `true` is returned. Otherwise96 * the given `type` is matched by an exact match, and then subtypes. You97 * may pass the subtype such as "html" which is then converted internally98 * to "text/html" using the mime lookup table.99 *100 * Examples:101 * 102 * // Accept: text/html103 * req.accepts('html');104 * // => true105 *106 * // Accept: text/*; application/json107 * req.accepts('html');108 * req.accepts('text/html');109 * req.accepts('text/plain');110 * req.accepts('application/json');111 * // => true112 *113 * req.accepts('image/png');114 * req.accepts('png');115 * // => false116 *117 * @param {String} type118 * @return {Boolean}119 * @api public120 */121122req.accepts = function(type){

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 123–124why, one step back
123 var accept = this.header('Accept')
124 , type = String(type);

fixed a jade testTj Holowaychukbefore adoption8f79856

line 125why, one step back
125

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 126–128why, one step back
126 // when not present or "*/*" accept anything
127 if (!accept || '*/*' == accept) return true;128

fixed a jade testTj Holowaychukbefore adoption8f79856

line 129why, one step back
129 // normalize extensions ".json" -> "json"

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

line 130why, one step back
130 if ('.' == type[0]) type = type.substr(1);

fixed a jade testTj Holowaychukbefore adoption8f79856

line 131why, one step back
131

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 132–133why, one step back
132 // allow "html" vs "text/html" etc
133 if (!~type.indexOf('/')) type = mime.lookup(type);

fixed a jade testTj Holowaychukbefore adoption8f79856

line 134why, one step back
134

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 135–136why, one step back
135 // check if we have a direct match
136 if (~accept.indexOf(type)) return true;

fixed a jade testTj Holowaychukbefore adoption8f79856

line 137why, one step back
137

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 138–140why, one step back
138 // check if we have type/*
139 type = type.split('/')[0] + '/*';140 return !! ~accept.indexOf(type);

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 141–226why, one step back
141};
142143/**144 * Return the value of param `name` when present or `defaultValue`.145 *146 * - Checks route placeholders, ex: _/user/:id_147 * - Checks query string params, ex: ?id=12148 * - Checks urlencoded body params, ex: id=12149 *150 * To utilize urlencoded request bodies, `req.body`151 * should be an object. This can be done by using152 * the `connect.bodyParser` middleware.153 *154 * @param {String} name155 * @param {Mixed} defaultValue156 * @return {String}157 * @api public158 */159160req.param = function(name, defaultValue){161 // route params like /user/:id162 if (this.params163 && this.params.hasOwnProperty(name)164 && undefined !== this.params[name]) {165 return this.params[name]; 166 }167 // query string params168 if (undefined !== this.query[name]) return this.query[name]; 169170 // request body params via connect.bodyParser171 if (this.body && undefined !== this.body[name]) return this.body[name];172173 return defaultValue;174};175176/**177 * Queue flash `msg` of the given `type`.178 *179 * This method is aliased as `req.notify()`.180 *181 * Examples:182 *183 * req.notify('info', 'email sent');184 * req.notify('info', 'email sent');185 * req.notify('error', 'email delivery failed');186 * req.notify('info', 'email re-sent');187 * // => 2188 *189 * req.notify('info');190 * // => ['email sent', 'email re-sent']191 *192 * req.notify('info');193 * // => []194 *195 * req.notify();196 * // => { error: ['email delivery failed'], info: [] }197 *198 * Formatting:199 *200 * Flash notifications also support arbitrary formatting support.201 * For example you may pass variable arguments to `req.notify()`202 * and use the %s specifier to be replaced by the associated argument:203 *204 * req.notify('info', 'email has been sent to %s.', userName);205 *206 * You may add addition formatters by defining `app.formatters`,207 * for example in the following snippet we define `%u` to uppercase208 * a string:209 *210 * app.formatters = {211 * u: function(val){212 * return String(val).toUpperCase();213 * }214 * };215 *216 * @param {String} type217 * @param {String} msg218 * @return {Array|Object|Number}219 * @api public220 */221222req.notify = function(type, msg){223 var sess = this.session;224 if (null == sess) throw Error('req.notify() requires sessions');225 var msgs = sess.notifications = sess.notifications || {};226

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

lines 227–242why, one step back
227 switch (arguments.length) {
228 // flush all messages229 case 0:230 sess.notifications = {};231 return msgs232 // flush messages for a specific type233 case 1:234 var arr = msgs[type];235 delete msgs[type];236 return arr || [];237 // set notification message238 default:239 var i = 2240 , args = arguments241 , formatters = this.app.formatters || {};242 formatters.__proto__ = defaultFormatters;

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

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

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

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

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

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

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

lines 247–248why, one step back
247 });
248 return (msgs[type] = msgs[type] || []).push(msg);

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 249–306why, one step back
249 }
250};251252/**253 * Check if the incoming request contains the "Content-Type" 254 * header field, and it contains the give mime `type`.255 *256 * Examples:257 *258 * // With Content-Type: text/html; charset=utf-8259 * req.is('html');260 * req.is('text/html');261 * // => true262 * 263 * // When Content-Type is application/json264 * req.is('json');265 * req.is('application/json');266 * // => true267 * 268 * req.is('html');269 * // => false270 * 271 * Ad-hoc callbacks can also be registered with Express, to perform272 * assertions again the request, for example if we need an expressive273 * way to check if our incoming request is an image, we can register "an image"274 * callback:275 * 276 * app.is('an image', function(req){277 * return 0 == req.headers['content-type'].indexOf('image');278 * });279 *280 * app.is('an attachment', function(req){281 * return 0 == req.headers['content-disposition'].indexOf('attachment');282 * });283 *284 * Now within our route callbacks, we can use to to assert content types285 * such as "image/jpeg", "image/png", etc.286 * 287 * app.post('/image/upload', function(req, res, next){288 * if (req.is('an image')) {289 * // do something290 * } else {291 * next();292 * }293 * });294 * 295 * @param {String} type296 * @return {Boolean}297 * @api public298 */299300req.is = function(type){301 var fn = this.app.is(type);302 if (fn) return fn(this);303 var contentType = this.headers['content-type'];304 if (!contentType) return;305 if (!~type.indexOf('/')) type = mime.lookup(type);306 if (~type.indexOf('*')) {

semiTj Holowaychukbefore adoption82c78ec

line 307why, one step back
307 type = type.split('/');

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 308–313why, one step back
308 contentType = contentType.split('/');
309 if ('*' == type[0] && type[1] == contentType[1]) return true;310 if ('*' == type[1] && type[0] == contentType[0]) return true;311 }312 return !! ~contentType.indexOf(type);313};

move getters downTj Holowaychukbefore adoptiond6fabb6

lines 314–335why, one step back
314
315/**316 * Short-hand for `req.connection.encrypted`.317 *318 * @return {Boolean}319 * @api public320 */321322req.__defineGetter__('secure', function(){323 return req.connection.encrypted;324});325326/**327 * Short-hand for `require('url').parse(req.url).pathname`.328 *329 * @return {String}330 * @api public331 */332333req.__defineGetter__('path', function(){334 return parse(this.url).pathname;335});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 336–347why, one step back
336
337/**338 * Check if the request is fresh, aka339 * Last-Modified and/or the ETag340 * still match.341 *342 * @return {Boolean}343 * @api public344 */345346req.__defineGetter__('fresh', function(){347 return ! this.stale;

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 348why, one step back
348});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 349–360why, one step back
349
350/**351 * Check if the request is stale, aka352 * Last-Modified and/or the ETag for the353 * resource has changed.354 *355 * @return {Boolean}356 * @api public357 */358359req.__defineGetter__('stale', function(){360 return connect.utils.modified(this, this.res);

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 361why, one step back
361});

fixed a jade testTj Holowaychukbefore adoption8f79856

lines 362–377why, one step back
362
363// Callback for isXMLHttpRequest / xhr364365function isxhr() {366 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';367}368369/**370 * Check if the request was an _XMLHttpRequest_.371 *372 * @return {Boolean}373 * @api public374 */375376req.__defineGetter__('isXMLHttpRequest', isxhr);377req.__defineGetter__('xhr', isxhr);