Skip to content
Myr

request.js

This file

Path

lib/request.js

465 lines · 10.4 KiB · JavaScript

Last changed by

mergedTj Holowaychukbefore adoption547d18c

History of this file

Take it

12/*!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')14  , connect = require('connect')15  , parse = require('url').parse16  , mime = require('mime');1718/**19 * Request prototype.20 */2122var req = exports = module.exports = {23  __proto__: http.IncomingMessage.prototype24};2526/**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  // TODO: rename... add tests, make .get() .header()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/**101 * Check if the given `type` is acceptable,102 * otherwise you should respond with 406 "Not Acceptable".103 *104 * Examples:105 * 106 *     // Accept: text/html107 *     req.accepts('html');108 *     // => true109 *110 *     // Accept: text/*; application/json111 *     req.accepts('html');112 *     req.accepts('text/html');113 *     req.accepts('text/plain');114 *     req.accepts('application/json');115 *     // => true116 *117 *     req.accepts('image/png');118 *     req.accepts('png');119 *     // => false120 *121 * @param {String} type122 * @return {Boolean}123 * @api public124 */125126req.accepts = function(type){127  return utils.accepts(type, this.header('Accept'));128};129130/**131 * Check if the given `charset` is acceptable,132 * otherwise you should respond with 406 "Not Acceptable".133 *134 * @param {String} charset135 * @return {Boolean}136 * @api public137 */138139req.acceptsCharset = function(charset){140  var accepted = this.acceptedCharsets;141  return accepted.length142    ? ~accepted.indexOf(charset)143    : true;144};145146/**147 * Check if the given `lang` is acceptable,148 * otherwise you should respond with 406 "Not Acceptable".149 *150 * @param {String} lang151 * @return {Boolean}152 * @api public153 */154155req.acceptsLanguage = function(lang){156  var accepted = this.acceptedLanguages;157  return accepted.length158    ? ~accepted.indexOf(lang)159    : true;160};161162/**163 * Return an array of Accepted media types164 * ordered from highest quality to lowest.165 *166 * Examples:167 *168 *     [ { value: 'application/json',169 *         quality: 1,170 *         type: 'application',171 *         subtype: 'json' },172 *       { value: 'text/html',173 *         quality: 0.5,174 *         type: 'text',175 *         subtype: 'html' } ]176 *177 * @return {Array}178 * @api public179 */180181req.__defineGetter__('accepted', function(){182  var accept = this.header('Accept');183  return accept184    ? utils.parseAccept(accept)185    : [];186});187188/**189 * Return an array of Accepted languages190 * ordered from highest quality to lowest.191 *192 * Examples:193 *194 *     Accept-Language: en;q=.5, en-us195 *     ['en-us', 'en']196 *197 * @return {Array}198 * @api public199 */200201req.__defineGetter__('acceptedLanguages', function(){202  var accept = this.header('Accept-Language');203  return accept204    ? utils205      .parseQuality(accept)206      .map(function(obj){207        return obj.value;208      })209    : [];210});211212/**213 * Return an array of Accepted charsets214 * ordered from highest quality to lowest.215 *216 * Examples:217 *218 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8219 *     ['unicode-1-1', 'iso-8859-5']220 *221 * @return {Array}222 * @api public223 */224225req.__defineGetter__('acceptedCharsets', function(){226  var accept = this.header('Accept-Charset');227  return accept228    ? utils229      .parseQuality(accept)230      .map(function(obj){231        return obj.value;232      })233    : [];234});235236/**237 * Return the value of param `name` when present or `defaultValue`.238 *239 *  - Checks route placeholders, ex: _/user/:id_240 *  - Checks query string params, ex: ?id=12241 *  - Checks urlencoded body params, ex: id=12242 *243 * To utilize urlencoded request bodies, `req.body`244 * should be an object. This can be done by using245 * the `connect.bodyParser` middleware.246 *247 * @param {String} name248 * @param {Mixed} defaultValue249 * @return {String}250 * @api public251 */252253req.param = function(name, defaultValue){254  // route params like /user/:id255  if (this.params256    && this.params.hasOwnProperty(name)257    && undefined !== this.params[name]) {258    return this.params[name]; 259  }260  // query string params261  if (undefined !== this.query[name]) return this.query[name]; 262263  // request body params via connect.bodyParser264  if (this.body && undefined !== this.body[name]) return this.body[name];265266  return defaultValue;267};268269/**270 * Queue flash `msg` of the given `type`.271 *272 * This method is aliased as `req.notify()`.273 *274 * Examples:275 *276 *      req.notify('info', 'email sent');277 *      req.notify('info', 'email sent');278 *      req.notify('error', 'email delivery failed');279 *      req.notify('info', 'email re-sent');280 *      // => 2281 *282 *      req.notify('info');283 *      // => ['email sent', 'email re-sent']284 *285 *      req.notify('info');286 *      // => []287 *288 *      req.notify();289 *      // => { error: ['email delivery failed'], info: [] }290 *291 * Formatting:292 *293 * Flash notifications also support arbitrary formatting support.294 * For example you may pass variable arguments to `req.notify()`295 * and use the %s specifier to be replaced by the associated argument:296 *297 *     req.notify('info', 'email has been sent to %s.', userName);298 *299 * You may add addition formatters by defining `app.formatters`,300 * for example in the following snippet we define `%u` to uppercase301 * a string:302 *303 *      app.formatters = {304 *        u: function(val){305 *          return String(val).toUpperCase();306 *        }307 *      };308 *309 * @param {String} type310 * @param {String} msg311 * @return {Array|Object|Number}312 * @api public313 */314315req.notify = function(type, msg){316  var sess = this.session;317  if (null == sess) throw Error('req.notify() requires sessions');318  var msgs = sess.notifications = sess.notifications || {};319320  switch (arguments.length) {321    // flush all messages322    case 0:323      sess.notifications = {};324      return msgs325    // flush messages for a specific type326    case 1:327      var arr = msgs[type];328      delete msgs[type];329      return arr || [];330    // set notification message331    default:332      var i = 2333        , args = arguments334        , formatters = this.app.formatters || {};335      formatters.__proto__ = defaultFormatters;336      msg = utils.miniMarkdown(msg);337      msg = msg.replace(/%([a-zA-Z])/g, function(_, format){338        var formatter = formatters[format];339        if (formatter) return formatter(utils.escape(args[i++]));340      });341      return (msgs[type] = msgs[type] || []).push(msg);342  }343};344345/**346 * Check if the incoming request contains the "Content-Type" 347 * header field, and it contains the give mime `type`.348 *349 * Examples:350 *351 *      // With Content-Type: text/html; charset=utf-8352 *      req.is('html');353 *      req.is('text/html');354 *      // => true355 *     356 *      // When Content-Type is application/json357 *      req.is('json');358 *      req.is('application/json');359 *      // => true360 *     361 *      req.is('html');362 *      // => false363 * 364 * Ad-hoc callbacks can also be registered with Express, to perform365 * assertions again the request, for example if we need an expressive366 * way to check if our incoming request is an image, we can register "an image"367 * callback:368 * 369 *       app.is('an image', function(req){370 *         return 0 == req.headers['content-type'].indexOf('image');371 *       });372 *373 *       app.is('an attachment', function(req){374 *         return 0 == req.headers['content-disposition'].indexOf('attachment');375 *       });376 *377 *  Now within our route callbacks, we can use to to assert content types378 *  such as "image/jpeg", "image/png", etc.379 * 380 *      app.post('/image/upload', function(req, res, next){381 *        if (req.is('an image')) {382 *          // do something383 *        } else {384 *          next();385 *        }386 *      });387 * 388 * @param {String} type389 * @return {Boolean}390 * @api public391 */392393req.is = function(type){394  var fn = this.app.is(type);395  if (fn) return fn(this);396  var contentType = this.headers['content-type'];397  if (!contentType) return;398  if (!~type.indexOf('/')) type = mime.lookup(type);399  if (~type.indexOf('*')) {400    type = type.split('/');401    contentType = contentType.split('/');402    if ('*' == type[0] && type[1] == contentType[1]) return true;403    if ('*' == type[1] && type[0] == contentType[0]) return true;404  }405  return !! ~contentType.indexOf(type);406};407408/**409 * Short-hand for `req.connection.encrypted`.410 *411 * @return {Boolean}412 * @api public413 */414415req.__defineGetter__('secure', function(){416  return req.connection.encrypted;417});418419/**420 * Short-hand for `require('url').parse(req.url).pathname`.421 *422 * @return {String}423 * @api public424 */425426req.__defineGetter__('path', function(){427  return parse(this.url).pathname;428});429430/**431 * Check if the request is fresh, aka432 * Last-Modified and/or the ETag433 * still match.434 *435 * @return {Boolean}436 * @api public437 */438439req.__defineGetter__('fresh', function(){440  return ! this.stale;441});442443/**444 * Check if the request is stale, aka445 * Last-Modified and/or the ETag for the446 * resource has changed.447 *448 * @return {Boolean}449 * @api public450 */451452req.__defineGetter__('stale', function(){453  return connect.utils.modified(this, this.res);454});455456/**457 * Check if the request was an _XMLHttpRequest_.458 *459 * @return {Boolean}460 * @api public461 */462463req.__defineGetter__('xhr', function(){464  return 'xmlhttprequest' == this.header('X-Requested-With', '').toLowerCase();465});