Skip to content
Myr

request.js

This file

Path

lib/request.js

405 lines · 9.5 KiB · JavaScript

Last changed by

Added req.acceptedTJ Holowaychukbefore adoptiona8fd8cb

History of this file

Take it

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

removed old view.jsTj Holowaychukbefore adoptioncecbaf2

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

removed old view.jsTj Holowaychukbefore adoptioncecbaf2

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};

removed old view.jsTj Holowaychukbefore adoptioncecbaf2

lines 25–150why, 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){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};9899/**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/**

Added req.acceptedTJ Holowaychukbefore adoptiona8fd8cb

lines 151–176why, one step back
151 * Return an array of Accepted media types
152 * ordered from highest quality to lowest.153 *154 * Examples:155 *156 * [ { value: 'application/json',157 * quality: 1,158 * type: 'application',159 * subtype: 'json' },160 * { value: 'text/html',161 * quality: 0.5,162 * type: 'text',163 * subtype: 'html' } ]164 *165 * @return {Array}166 * @api public167 */168169req.__defineGetter__('accepted', function(){170 var accept = this.header('Accept');171 return accept172 ? utils.parseAccept(accept)173 : [];174});175176/**

removed old view.jsTj Holowaychukbefore adoptioncecbaf2

lines 177–346why, one step back
177 * Return the value of param `name` when present or `defaultValue`.
178 *179 * - Checks route placeholders, ex: _/user/:id_180 * - Checks query string params, ex: ?id=12181 * - Checks urlencoded body params, ex: id=12182 *183 * To utilize urlencoded request bodies, `req.body`184 * should be an object. This can be done by using185 * the `connect.bodyParser` middleware.186 *187 * @param {String} name188 * @param {Mixed} defaultValue189 * @return {String}190 * @api public191 */192193req.param = function(name, defaultValue){194 // route params like /user/:id195 if (this.params196 && this.params.hasOwnProperty(name)197 && undefined !== this.params[name]) {198 return this.params[name]; 199 }200 // query string params201 if (undefined !== this.query[name]) return this.query[name]; 202203 // request body params via connect.bodyParser204 if (this.body && undefined !== this.body[name]) return this.body[name];205206 return defaultValue;207};208209/**210 * Queue flash `msg` of the given `type`.211 *212 * This method is aliased as `req.notify()`.213 *214 * Examples:215 *216 * req.notify('info', 'email sent');217 * req.notify('info', 'email sent');218 * req.notify('error', 'email delivery failed');219 * req.notify('info', 'email re-sent');220 * // => 2221 *222 * req.notify('info');223 * // => ['email sent', 'email re-sent']224 *225 * req.notify('info');226 * // => []227 *228 * req.notify();229 * // => { error: ['email delivery failed'], info: [] }230 *231 * Formatting:232 *233 * Flash notifications also support arbitrary formatting support.234 * For example you may pass variable arguments to `req.notify()`235 * and use the %s specifier to be replaced by the associated argument:236 *237 * req.notify('info', 'email has been sent to %s.', userName);238 *239 * You may add addition formatters by defining `app.formatters`,240 * for example in the following snippet we define `%u` to uppercase241 * a string:242 *243 * app.formatters = {244 * u: function(val){245 * return String(val).toUpperCase();246 * }247 * };248 *249 * @param {String} type250 * @param {String} msg251 * @return {Array|Object|Number}252 * @api public253 */254255req.notify = function(type, msg){256 var sess = this.session;257 if (null == sess) throw Error('req.notify() requires sessions');258 var msgs = sess.notifications = sess.notifications || {};259260 switch (arguments.length) {261 // flush all messages262 case 0:263 sess.notifications = {};264 return msgs265 // flush messages for a specific type266 case 1:267 var arr = msgs[type];268 delete msgs[type];269 return arr || [];270 // set notification message271 default:272 var i = 2273 , args = arguments274 , formatters = this.app.formatters || {};275 formatters.__proto__ = defaultFormatters;276 msg = utils.miniMarkdown(msg);277 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){278 var formatter = formatters[format];279 if (formatter) return formatter(utils.escape(args[i++]));280 });281 return (msgs[type] = msgs[type] || []).push(msg);282 }283};284285/**286 * Check if the incoming request contains the "Content-Type" 287 * header field, and it contains the give mime `type`.288 *289 * Examples:290 *291 * // With Content-Type: text/html; charset=utf-8292 * req.is('html');293 * req.is('text/html');294 * // => true295 * 296 * // When Content-Type is application/json297 * req.is('json');298 * req.is('application/json');299 * // => true300 * 301 * req.is('html');302 * // => false303 * 304 * Ad-hoc callbacks can also be registered with Express, to perform305 * assertions again the request, for example if we need an expressive306 * way to check if our incoming request is an image, we can register "an image"307 * callback:308 * 309 * app.is('an image', function(req){310 * return 0 == req.headers['content-type'].indexOf('image');311 * });312 *313 * app.is('an attachment', function(req){314 * return 0 == req.headers['content-disposition'].indexOf('attachment');315 * });316 *317 * Now within our route callbacks, we can use to to assert content types318 * such as "image/jpeg", "image/png", etc.319 * 320 * app.post('/image/upload', function(req, res, next){321 * if (req.is('an image')) {322 * // do something323 * } else {324 * next();325 * }326 * });327 * 328 * @param {String} type329 * @return {Boolean}330 * @api public331 */332333req.is = function(type){334 var fn = this.app.is(type);335 if (fn) return fn(this);336 var contentType = this.headers['content-type'];337 if (!contentType) return;338 if (!~type.indexOf('/')) type = mime.lookup(type);339 if (~type.indexOf('*')) {340 type = type.split('/');341 contentType = contentType.split('/');342 if ('*' == type[0] && type[1] == contentType[1]) return true;343 if ('*' == type[1] && type[0] == contentType[0]) return true;344 }345 return !! ~contentType.indexOf(type);346};

move getters downTj Holowaychukbefore adoptiond6fabb6

lines 347–368why, one step back
347
348/**349 * Short-hand for `req.connection.encrypted`.350 *351 * @return {Boolean}352 * @api public353 */354355req.__defineGetter__('secure', function(){356 return req.connection.encrypted;357});358359/**360 * Short-hand for `require('url').parse(req.url).pathname`.361 *362 * @return {String}363 * @api public364 */365366req.__defineGetter__('path', function(){367 return parse(this.url).pathname;368});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 369–380why, one step back
369
370/**371 * Check if the request is fresh, aka372 * Last-Modified and/or the ETag373 * still match.374 *375 * @return {Boolean}376 * @api public377 */378379req.__defineGetter__('fresh', function(){380 return ! this.stale;

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 381why, one step back
381});

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 382–393why, one step back
382
383/**384 * Check if the request is stale, aka385 * Last-Modified and/or the ETag for the386 * resource has changed.387 *388 * @return {Boolean}389 * @api public390 */391392req.__defineGetter__('stale', function(){393 return connect.utils.modified(this, this.res);

semicolonsTj Holowaychukbefore adoption1a1ed0a

line 394why, one step back
394});

removed old view.jsTj Holowaychukbefore adoptioncecbaf2

lines 395–402why, one step back
395
396/**397 * Check if the request was an _XMLHttpRequest_.398 *399 * @return {Boolean}400 * @api public401 */402

Removed req.isXMLHttpRequestTj Holowaychukbefore adoptionaf46df7

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

case sensitivity testTj Holowaychukbefore adoption1a5636b

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

Removed req.isXMLHttpRequestTj Holowaychukbefore adoptionaf46df7

line 405why, one step back
405});