Skip to content
Myr

request.js

This file

Path

lib/request.js

429 lines · 9.9 KiB · JavaScript

Last changed by

Added req.acceptedLanguagesTJ Holowaychukbefore adoptione8c3736

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  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/**151 * Return an array of Accepted media types152 * 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/**177 * Return an array of Accepted languages178 * ordered from highest quality to lowest.179 *180 * Examples:181 *182 *     Accept-Language: en;q=.5, en-us183 *     ['en-us', 'en']184 *185 * @return {Array}186 * @api public187 */188189req.__defineGetter__('acceptedLanguages', function(){190  var accept = this.header('Accept-Language');191  return accept192    ? utils193      .parseQuality(accept)194      .map(function(obj){195        return obj.value;196      })197    : [];198});199200/**201 * Return the value of param `name` when present or `defaultValue`.202 *203 *  - Checks route placeholders, ex: _/user/:id_204 *  - Checks query string params, ex: ?id=12205 *  - Checks urlencoded body params, ex: id=12206 *207 * To utilize urlencoded request bodies, `req.body`208 * should be an object. This can be done by using209 * the `connect.bodyParser` middleware.210 *211 * @param {String} name212 * @param {Mixed} defaultValue213 * @return {String}214 * @api public215 */216217req.param = function(name, defaultValue){218  // route params like /user/:id219  if (this.params220    && this.params.hasOwnProperty(name)221    && undefined !== this.params[name]) {222    return this.params[name]; 223  }224  // query string params225  if (undefined !== this.query[name]) return this.query[name]; 226227  // request body params via connect.bodyParser228  if (this.body && undefined !== this.body[name]) return this.body[name];229230  return defaultValue;231};232233/**234 * Queue flash `msg` of the given `type`.235 *236 * This method is aliased as `req.notify()`.237 *238 * Examples:239 *240 *      req.notify('info', 'email sent');241 *      req.notify('info', 'email sent');242 *      req.notify('error', 'email delivery failed');243 *      req.notify('info', 'email re-sent');244 *      // => 2245 *246 *      req.notify('info');247 *      // => ['email sent', 'email re-sent']248 *249 *      req.notify('info');250 *      // => []251 *252 *      req.notify();253 *      // => { error: ['email delivery failed'], info: [] }254 *255 * Formatting:256 *257 * Flash notifications also support arbitrary formatting support.258 * For example you may pass variable arguments to `req.notify()`259 * and use the %s specifier to be replaced by the associated argument:260 *261 *     req.notify('info', 'email has been sent to %s.', userName);262 *263 * You may add addition formatters by defining `app.formatters`,264 * for example in the following snippet we define `%u` to uppercase265 * a string:266 *267 *      app.formatters = {268 *        u: function(val){269 *          return String(val).toUpperCase();270 *        }271 *      };272 *273 * @param {String} type274 * @param {String} msg275 * @return {Array|Object|Number}276 * @api public277 */278279req.notify = function(type, msg){280  var sess = this.session;281  if (null == sess) throw Error('req.notify() requires sessions');282  var msgs = sess.notifications = sess.notifications || {};283284  switch (arguments.length) {285    // flush all messages286    case 0:287      sess.notifications = {};288      return msgs289    // flush messages for a specific type290    case 1:291      var arr = msgs[type];292      delete msgs[type];293      return arr || [];294    // set notification message295    default:296      var i = 2297        , args = arguments298        , formatters = this.app.formatters || {};299      formatters.__proto__ = defaultFormatters;300      msg = utils.miniMarkdown(msg);301      msg = msg.replace(/%([a-zA-Z])/g, function(_, format){302        var formatter = formatters[format];303        if (formatter) return formatter(utils.escape(args[i++]));304      });305      return (msgs[type] = msgs[type] || []).push(msg);306  }307};308309/**310 * Check if the incoming request contains the "Content-Type" 311 * header field, and it contains the give mime `type`.312 *313 * Examples:314 *315 *      // With Content-Type: text/html; charset=utf-8316 *      req.is('html');317 *      req.is('text/html');318 *      // => true319 *     320 *      // When Content-Type is application/json321 *      req.is('json');322 *      req.is('application/json');323 *      // => true324 *     325 *      req.is('html');326 *      // => false327 * 328 * Ad-hoc callbacks can also be registered with Express, to perform329 * assertions again the request, for example if we need an expressive330 * way to check if our incoming request is an image, we can register "an image"331 * callback:332 * 333 *       app.is('an image', function(req){334 *         return 0 == req.headers['content-type'].indexOf('image');335 *       });336 *337 *       app.is('an attachment', function(req){338 *         return 0 == req.headers['content-disposition'].indexOf('attachment');339 *       });340 *341 *  Now within our route callbacks, we can use to to assert content types342 *  such as "image/jpeg", "image/png", etc.343 * 344 *      app.post('/image/upload', function(req, res, next){345 *        if (req.is('an image')) {346 *          // do something347 *        } else {348 *          next();349 *        }350 *      });351 * 352 * @param {String} type353 * @return {Boolean}354 * @api public355 */356357req.is = function(type){358  var fn = this.app.is(type);359  if (fn) return fn(this);360  var contentType = this.headers['content-type'];361  if (!contentType) return;362  if (!~type.indexOf('/')) type = mime.lookup(type);363  if (~type.indexOf('*')) {364    type = type.split('/');365    contentType = contentType.split('/');366    if ('*' == type[0] && type[1] == contentType[1]) return true;367    if ('*' == type[1] && type[0] == contentType[0]) return true;368  }369  return !! ~contentType.indexOf(type);370};371372/**373 * Short-hand for `req.connection.encrypted`.374 *375 * @return {Boolean}376 * @api public377 */378379req.__defineGetter__('secure', function(){380  return req.connection.encrypted;381});382383/**384 * Short-hand for `require('url').parse(req.url).pathname`.385 *386 * @return {String}387 * @api public388 */389390req.__defineGetter__('path', function(){391  return parse(this.url).pathname;392});393394/**395 * Check if the request is fresh, aka396 * Last-Modified and/or the ETag397 * still match.398 *399 * @return {Boolean}400 * @api public401 */402403req.__defineGetter__('fresh', function(){404  return ! this.stale;405});406407/**408 * Check if the request is stale, aka409 * Last-Modified and/or the ETag for the410 * resource has changed.411 *412 * @return {Boolean}413 * @api public414 */415416req.__defineGetter__('stale', function(){417  return connect.utils.modified(this, this.res);418});419420/**421 * Check if the request was an _XMLHttpRequest_.422 *423 * @return {Boolean}424 * @api public425 */426427req.__defineGetter__('xhr', function(){428  return 'xmlhttprequest' == this.header('X-Requested-With', '').toLowerCase();429});