Skip to content
Myr

request.js

This file

Path

lib/request.js

435 lines · 9.8 KiB · JavaScript

Last changed by

refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06

History of this file

Take it

12/**3 * Module dependencies.4 */56var accepts = require('accepts');7var typeis = require('type-is');8var http = require('http')9  , utils = require('./utils')10  , connect = require('connect')11  , fresh = require('fresh')12  , parseRange = require('range-parser')13  , parse = connect.utils.parseUrl14  , mime = connect.mime;1516/**17 * Request prototype.18 */1920var req = exports = module.exports = {21  __proto__: http.IncomingMessage.prototype22};2324/**25 * Return request header.26 *27 * The `Referrer` header field is special-cased,28 * both `Referrer` and `Referer` are interchangeable.29 *30 * Examples:31 *32 *     req.get('Content-Type');33 *     // => "text/plain"34 *35 *     req.get('content-type');36 *     // => "text/plain"37 *38 *     req.get('Something');39 *     // => undefined40 *41 * Aliased as `req.header()`.42 *43 * @param {String} name44 * @return {String}45 * @api public46 */4748req.get =49req.header = function(name){50  switch (name = name.toLowerCase()) {51    case 'referer':52    case 'referrer':53      return this.headers.referrer54        || this.headers.referer;55    default:56      return this.headers[name];57  }58};5960/**61 * To do: update docs.62 *63 * Check if the given `type(s)` is acceptable, returning64 * the best match when true, otherwise `undefined`, in which65 * case you should respond with 406 "Not Acceptable".66 *67 * The `type` value may be a single mime type string68 * such as "application/json", the extension name69 * such as "json", a comma-delimted list such as "json, html, text/plain",70 * an argument list such as `"json", "html", "text/plain"`,71 * or an array `["json", "html", "text/plain"]`. When a list72 * or array is given the _best_ match, if any is returned.73 *74 * Examples:75 *76 *     // Accept: text/html77 *     req.accepts('html');78 *     // => "html"79 *80 *     // Accept: text/*, application/json81 *     req.accepts('html');82 *     // => "html"83 *     req.accepts('text/html');84 *     // => "text/html"85 *     req.accepts('json, text');86 *     // => "json"87 *     req.accepts('application/json');88 *     // => "application/json"89 *90 *     // Accept: text/*, application/json91 *     req.accepts('image/png');92 *     req.accepts('png');93 *     // => undefined94 *95 *     // Accept: text/*;q=.5, application/json96 *     req.accepts(['html', 'json']);97 *     req.accepts('html', 'json');98 *     req.accepts('html, json');99 *     // => "json"100 *101 * @param {String|Array} type(s)102 * @return {String}103 * @api public104 */105106req.accepts = function(){107  var accept = accepts(this);108  return accept.types.apply(accept, arguments);109};110111/**112 * Check if the given `encoding` is accepted.113 *114 * @param {String} encoding115 * @return {Boolean}116 * @api public117 */118119req.acceptsEncoding = // backwards compatibility120req.acceptsEncodings = function(){121  var accept = accepts(this);122  return accept.encodings.apply(accept, arguments);123};124125/**126 * To do: update docs.127 *128 * Check if the given `charset` is acceptable,129 * otherwise you should respond with 406 "Not Acceptable".130 *131 * @param {String} charset132 * @return {Boolean}133 * @api public134 */135136req.acceptsCharset = // backwards compatibility137req.acceptsCharsets = function(){138  var accept = accepts(this);139  return accept.charsets.apply(accept, arguments);140};141142/**143 * To do: update docs.144 *145 * Check if the given `lang` is acceptable,146 * otherwise you should respond with 406 "Not Acceptable".147 *148 * @param {String} lang149 * @return {Boolean}150 * @api public151 */152153req.acceptsLanguage = // backwards compatibility154req.acceptsLanguages = function(lang){155  var accept = accepts(this);156  return accept.languages.apply(accept, arguments);157};158159/**160 * Parse Range header field,161 * capping to the given `size`.162 *163 * Unspecified ranges such as "0-" require164 * knowledge of your resource length. In165 * the case of a byte range this is of course166 * the total number of bytes. If the Range167 * header field is not given `null` is returned,168 * `-1` when unsatisfiable, `-2` when syntactically invalid.169 *170 * NOTE: remember that ranges are inclusive, so171 * for example "Range: users=0-3" should respond172 * with 4 users when available, not 3.173 *174 * @param {Number} size175 * @return {Array}176 * @api public177 */178179req.range = function(size){180  var range = this.get('Range');181  if (!range) return;182  return parseRange(size, range);183};184185/**186 * Return the value of param `name` when present or `defaultValue`.187 *188 *  - Checks route placeholders, ex: _/user/:id_189 *  - Checks body params, ex: id=12, {"id":12}190 *  - Checks query string params, ex: ?id=12191 *192 * To utilize request bodies, `req.body`193 * should be an object. This can be done by using194 * the `connect.bodyParser()` middleware.195 *196 * @param {String} name197 * @param {Mixed} [defaultValue]198 * @return {String}199 * @api public200 */201202req.param = function(name, defaultValue){203  var params = this.params || {};204  var body = this.body || {};205  var query = this.query || {};206  if (null != params[name] && params.hasOwnProperty(name)) return params[name];207  if (null != body[name]) return body[name];208  if (null != query[name]) return query[name];209  return defaultValue;210};211212/**213 * Check if the incoming request contains the "Content-Type"214 * header field, and it contains the give mime `type`.215 *216 * Examples:217 *218 *      // With Content-Type: text/html; charset=utf-8219 *      req.is('html');220 *      req.is('text/html');221 *      req.is('text/*');222 *      // => true223 *224 *      // When Content-Type is application/json225 *      req.is('json');226 *      req.is('application/json');227 *      req.is('application/*');228 *      // => true229 *230 *      req.is('html');231 *      // => false232 *233 * @param {String} type234 * @return {Boolean}235 * @api public236 */237238req.is = function(types){239  if (!Array.isArray(types)) types = [].slice.call(arguments);240  return typeis(this, types);241};242243/**244 * Return the protocol string "http" or "https"245 * when requested with TLS. When the "trust proxy"246 * setting is enabled the "X-Forwarded-Proto" header247 * field will be trusted. If you're running behind248 * a reverse proxy that supplies https for you this249 * may be enabled.250 *251 * @return {String}252 * @api public253 */254255req.__defineGetter__('protocol', function(){256  var trustProxy = this.app.get('trust proxy');257  if (this.connection.encrypted) return 'https';258  if (!trustProxy) return 'http';259  var proto = this.get('X-Forwarded-Proto') || 'http';260  return proto.split(/\s*,\s*/)[0];261});262263/**264 * Short-hand for:265 *266 *    req.protocol == 'https'267 *268 * @return {Boolean}269 * @api public270 */271272req.__defineGetter__('secure', function(){273  return 'https' == this.protocol;274});275276/**277 * Return the remote address, or when278 * "trust proxy" is `true` return279 * the upstream addr.280 *281 * @return {String}282 * @api public283 */284285req.__defineGetter__('ip', function(){286  return this.ips[0] || this.connection.remoteAddress;287});288289/**290 * When "trust proxy" is `true`, parse291 * the "X-Forwarded-For" ip address list.292 *293 * For example if the value were "client, proxy1, proxy2"294 * you would receive the array `["client", "proxy1", "proxy2"]`295 * where "proxy2" is the furthest down-stream.296 *297 * @return {Array}298 * @api public299 */300301req.__defineGetter__('ips', function(){302  var trustProxy = this.app.get('trust proxy');303  var val = this.get('X-Forwarded-For');304  return trustProxy && val305    ? val.split(/ *, */)306    : [];307});308309/**310 * Return basic auth credentials.311 *312 * Examples:313 *314 *    // http://tobi:hello@example.com315 *    req.auth316 *    // => { username: 'tobi', password: 'hello' }317 *318 * @return {Object} or undefined319 * @api public320 */321322req.__defineGetter__('auth', function(){323  // missing324  var auth = this.get('Authorization');325  if (!auth) return;326327  // malformed328  var parts = auth.split(' ');329  if ('basic' != parts[0].toLowerCase()) return;330  if (!parts[1]) return;331  auth = parts[1];332333  // credentials334  auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);335  if (!auth) return;336  return { username: auth[1], password: auth[2] };337});338339/**340 * Return subdomains as an array.341 *342 * Subdomains are the dot-separated parts of the host before the main domain of343 * the app. By default, the domain of the app is assumed to be the last two344 * parts of the host. This can be changed by setting "subdomain offset".345 *346 * For example, if the domain is "tobi.ferrets.example.com":347 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.348 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.349 *350 * @return {Array}351 * @api public352 */353354req.__defineGetter__('subdomains', function(){355  var offset = this.app.get('subdomain offset');356  return (this.host || '')357    .split('.')358    .reverse()359    .slice(offset);360});361362/**363 * Short-hand for `url.parse(req.url).pathname`.364 *365 * @return {String}366 * @api public367 */368369req.__defineGetter__('path', function(){370  return parse(this).pathname;371});372373/**374 * Parse the "Host" header field hostname.375 *376 * @return {String}377 * @api public378 */379380req.__defineGetter__('host', function(){381  var trustProxy = this.app.get('trust proxy');382  var host = trustProxy && this.get('X-Forwarded-Host');383  host = host || this.get('Host');384  if (!host) return;385  return host.split(':')[0];386});387388/**389 * Check if the request is fresh, aka390 * Last-Modified and/or the ETag391 * still match.392 *393 * @return {Boolean}394 * @api public395 */396397req.__defineGetter__('fresh', function(){398  var method = this.method;399  var s = this.res.statusCode;400401  // GET or HEAD for weak freshness validation only402  if ('GET' != method && 'HEAD' != method) return false;403404  // 2xx or 304 as per rfc2616 14.26405  if ((s >= 200 && s < 300) || 304 == s) {406    return fresh(this.headers, this.res._headers);407  }408409  return false;410});411412/**413 * Check if the request is stale, aka414 * "Last-Modified" and / or the "ETag" for the415 * resource has changed.416 *417 * @return {Boolean}418 * @api public419 */420421req.__defineGetter__('stale', function(){422  return !this.fresh;423});424425/**426 * Check if the request was an _XMLHttpRequest_.427 *428 * @return {Boolean}429 * @api public430 */431432req.__defineGetter__('xhr', function(){433  var val = this.get('X-Requested-With') || '';434  return 'xmlhttprequest' == val.toLowerCase();435});