Skip to content
Myr

request.js

This file

Path

lib/request.js

526 lines · 11.4 KiB · JavaScript

Last changed by

return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b

History of this file

Take it

12/**3 * Module dependencies.4 */56var http = require('http')7  , utils = require('./utils')8  , connect = require('connect')9  , fresh = require('fresh')10  , parseRange = require('range-parser')11  , parse = connect.utils.parseUrl12  , mime = connect.mime;1314/**15 * Request prototype.16 */1718var req = exports = module.exports = {19  __proto__: http.IncomingMessage.prototype20};2122/**23 * Return request header.24 *25 * The `Referrer` header field is special-cased,26 * both `Referrer` and `Referer` are interchangeable.27 *28 * Examples:29 *30 *     req.get('Content-Type');31 *     // => "text/plain"32 *33 *     req.get('content-type');34 *     // => "text/plain"35 *36 *     req.get('Something');37 *     // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} name42 * @return {String}43 * @api public44 */4546req.get =47req.header = function(name){48  switch (name = name.toLowerCase()) {49    case 'referer':50    case 'referrer':51      return this.headers.referrer52        || this.headers.referer;53    default:54      return this.headers[name];55  }56};5758/**59 * Check if the given `type(s)` is acceptable, returning60 * the best match when true, otherwise `undefined`, in which61 * case you should respond with 406 "Not Acceptable".62 *63 * The `type` value may be a single mime type string64 * such as "application/json", the extension name65 * such as "json", a comma-delimted list such as "json, html, text/plain",66 * or an array `["json", "html", "text/plain"]`. When a list67 * or array is given the _best_ match, if any is returned.68 *69 * Examples:70 *71 *     // Accept: text/html72 *     req.accepts('html');73 *     // => "html"74 *75 *     // Accept: text/*, application/json76 *     req.accepts('html');77 *     // => "html"78 *     req.accepts('text/html');79 *     // => "text/html"80 *     req.accepts('json, text');81 *     // => "json"82 *     req.accepts('application/json');83 *     // => "application/json"84 *85 *     // Accept: text/*, application/json86 *     req.accepts('image/png');87 *     req.accepts('png');88 *     // => undefined89 *90 *     // Accept: text/*;q=.5, application/json91 *     req.accepts(['html', 'json']);92 *     req.accepts('html, json');93 *     // => "json"94 *95 * @param {String|Array} type(s)96 * @return {String}97 * @api public98 */99100req.accepts = function(type){101  return utils.accepts(type, this.get('Accept'));102};103104/**105 * Check if the given `encoding` is accepted.106 *107 * @param {String} encoding108 * @return {Boolean}109 * @api public110 */111112req.acceptsEncoding = function(encoding){113  return !! ~this.acceptedEncodings.indexOf(encoding);114};115116/**117 * Check if the given `charset` is acceptable,118 * otherwise you should respond with 406 "Not Acceptable".119 *120 * @param {String} charset121 * @return {Boolean}122 * @api public123 */124125req.acceptsCharset = function(charset){126  var accepted = this.acceptedCharsets;127  return accepted.length128    ? !! ~accepted.indexOf(charset)129    : true;130};131132/**133 * Check if the given `lang` is acceptable,134 * otherwise you should respond with 406 "Not Acceptable".135 *136 * @param {String} lang137 * @return {Boolean}138 * @api public139 */140141req.acceptsLanguage = function(lang){142  var accepted = this.acceptedLanguages;143  return accepted.length144    ? !! ~accepted.indexOf(lang)145    : true;146};147148/**149 * Parse Range header field,150 * capping to the given `size`.151 *152 * Unspecified ranges such as "0-" require153 * knowledge of your resource length. In154 * the case of a byte range this is of course155 * the total number of bytes. If the Range156 * header field is not given `null` is returned,157 * `-1` when unsatisfiable, `-2` when syntactically invalid.158 *159 * NOTE: remember that ranges are inclusive, so160 * for example "Range: users=0-3" should respond161 * with 4 users when available, not 3.162 *163 * @param {Number} size164 * @return {Array}165 * @api public166 */167168req.range = function(size){169  var range = this.get('Range');170  if (!range) return;171  return parseRange(size, range);172};173174/**175 * Return an array of encodings.176 *177 * Examples:178 *179 *     ['gzip', 'deflate']180 *181 * @return {Array}182 * @api public183 */184185req.__defineGetter__('acceptedEncodings', function(){186  var accept = this.get('Accept-Encoding');187  return accept188    ? accept.trim().split(/ *, */)189    : [];190});191192/**193 * Return an array of Accepted media types194 * ordered from highest quality to lowest.195 *196 * Examples:197 *198 *     [ { value: 'application/json',199 *         quality: 1,200 *         type: 'application',201 *         subtype: 'json' },202 *       { value: 'text/html',203 *         quality: 0.5,204 *         type: 'text',205 *         subtype: 'html' } ]206 *207 * @return {Array}208 * @api public209 */210211req.__defineGetter__('accepted', function(){212  var accept = this.get('Accept');213  return accept214    ? utils.parseAccept(accept)215    : [];216});217218/**219 * Return an array of Accepted languages220 * ordered from highest quality to lowest.221 *222 * Examples:223 *224 *     Accept-Language: en;q=.5, en-us225 *     ['en-us', 'en']226 *227 * @return {Array}228 * @api public229 */230231req.__defineGetter__('acceptedLanguages', function(){232  var accept = this.get('Accept-Language');233  return accept234    ? utils235      .parseParams(accept)236      .map(function(obj){237        return obj.value;238      })239    : [];240});241242/**243 * Return an array of Accepted charsets244 * ordered from highest quality to lowest.245 *246 * Examples:247 *248 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8249 *     ['unicode-1-1', 'iso-8859-5']250 *251 * @return {Array}252 * @api public253 */254255req.__defineGetter__('acceptedCharsets', function(){256  var accept = this.get('Accept-Charset');257  return accept258    ? utils259      .parseParams(accept)260      .map(function(obj){261        return obj.value;262      })263    : [];264});265266/**267 * Return the value of param `name` when present or `defaultValue`.268 *269 *  - Checks route placeholders, ex: _/user/:id_270 *  - Checks body params, ex: id=12, {"id":12}271 *  - Checks query string params, ex: ?id=12272 *273 * To utilize request bodies, `req.body`274 * should be an object. This can be done by using275 * the `connect.bodyParser()` middleware.276 *277 * @param {String} name278 * @param {Mixed} [defaultValue]279 * @return {String}280 * @api public281 */282283req.param = function(name, defaultValue){284  var params = this.params || {};285  var body = this.body || {};286  var query = this.query || {};287  if (null != params[name] && params.hasOwnProperty(name)) return params[name];288  if (null != body[name]) return body[name];289  if (null != query[name]) return query[name];290  return defaultValue;291};292293/**294 * Check if the incoming request contains the "Content-Type"295 * header field, and it contains the give mime `type`.296 *297 * Examples:298 *299 *      // With Content-Type: text/html; charset=utf-8300 *      req.is('html');301 *      req.is('text/html');302 *      req.is('text/*');303 *      // => true304 *305 *      // When Content-Type is application/json306 *      req.is('json');307 *      req.is('application/json');308 *      req.is('application/*');309 *      // => true310 *311 *      req.is('html');312 *      // => false313 *314 * @param {String} type315 * @return {Boolean}316 * @api public317 */318319req.is = function(type){320  var ct = this.get('Content-Type');321  if (!ct) return false;322  ct = ct.split(';')[0];323  if (!~type.indexOf('/')) type = mime.lookup(type);324  if (~type.indexOf('*')) {325    type = type.split('/');326    ct = ct.split('/');327    if ('*' == type[0] && type[1] == ct[1]) return true;328    if ('*' == type[1] && type[0] == ct[0]) return true;329    return false;330  }331  return !! ~ct.indexOf(type);332};333334/**335 * Return the protocol string "http" or "https"336 * when requested with TLS. When the "trust proxy"337 * setting is enabled the "X-Forwarded-Proto" header338 * field will be trusted. If you're running behind339 * a reverse proxy that supplies https for you this340 * may be enabled.341 *342 * @return {String}343 * @api public344 */345346req.__defineGetter__('protocol', function(){347  var trustProxy = this.app.get('trust proxy');348  if (this.connection.encrypted) return 'https';349  if (!trustProxy) return 'http';350  var proto = this.get('X-Forwarded-Proto') || 'http';351  return proto.split(/\s*,\s*/)[0];352});353354/**355 * Short-hand for:356 *357 *    req.protocol == 'https'358 *359 * @return {Boolean}360 * @api public361 */362363req.__defineGetter__('secure', function(){364  return 'https' == this.protocol;365});366367/**368 * Return the remote address, or when369 * "trust proxy" is `true` return370 * the upstream addr.371 *372 * @return {String}373 * @api public374 */375376req.__defineGetter__('ip', function(){377  return this.ips[0] || this.connection.remoteAddress;378});379380/**381 * When "trust proxy" is `true`, parse382 * the "X-Forwarded-For" ip address list.383 *384 * For example if the value were "client, proxy1, proxy2"385 * you would receive the array `["client", "proxy1", "proxy2"]`386 * where "proxy2" is the furthest down-stream.387 *388 * @return {Array}389 * @api public390 */391392req.__defineGetter__('ips', function(){393  var trustProxy = this.app.get('trust proxy');394  var val = this.get('X-Forwarded-For');395  return trustProxy && val396    ? val.split(/ *, */)397    : [];398});399400/**401 * Return basic auth credentials.402 *403 * Examples:404 *405 *    // http://tobi:hello@example.com406 *    req.auth407 *    // => { username: 'tobi', password: 'hello' }408 *409 * @return {Object} or undefined410 * @api public411 */412413req.__defineGetter__('auth', function(){414  // missing415  var auth = this.get('Authorization');416  if (!auth) return;417418  // malformed419  var parts = auth.split(' ');420  if ('basic' != parts[0].toLowerCase()) return;421  if (!parts[1]) return;422  auth = parts[1];423424  // credentials425  auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);426  if (!auth) return;427  return { username: auth[1], password: auth[2] };428});429430/**431 * Return subdomains as an array.432 *433 * Subdomains are the dot-separated parts of the host before the main domain of434 * the app. By default, the domain of the app is assumed to be the last two435 * parts of the host. This can be changed by setting "subdomain offset".436 *437 * For example, if the domain is "tobi.ferrets.example.com":438 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.439 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.440 *441 * @return {Array}442 * @api public443 */444445req.__defineGetter__('subdomains', function(){446  var offset = this.app.get('subdomain offset');447  return (this.host || '')448    .split('.')449    .reverse()450    .slice(offset);451});452453/**454 * Short-hand for `url.parse(req.url).pathname`.455 *456 * @return {String}457 * @api public458 */459460req.__defineGetter__('path', function(){461  return parse(this).pathname;462});463464/**465 * Parse the "Host" header field hostname.466 *467 * @return {String}468 * @api public469 */470471req.__defineGetter__('host', function(){472  var trustProxy = this.app.get('trust proxy');473  var host = trustProxy && this.get('X-Forwarded-Host');474  host = host || this.get('Host');475  if (!host) return;476  return host.split(':')[0];477});478479/**480 * Check if the request is fresh, aka481 * Last-Modified and/or the ETag482 * still match.483 *484 * @return {Boolean}485 * @api public486 */487488req.__defineGetter__('fresh', function(){489  var method = this.method;490  var s = this.res.statusCode;491492  // GET or HEAD for weak freshness validation only493  if ('GET' != method && 'HEAD' != method) return false;494495  // 2xx or 304 as per rfc2616 14.26496  if ((s >= 200 && s < 300) || 304 == s) {497    return fresh(this.headers, this.res._headers);498  }499500  return false;501});502503/**504 * Check if the request is stale, aka505 * "Last-Modified" and / or the "ETag" for the506 * resource has changed.507 *508 * @return {Boolean}509 * @api public510 */511512req.__defineGetter__('stale', function(){513  return !this.fresh;514});515516/**517 * Check if the request was an _XMLHttpRequest_.518 *519 * @return {Boolean}520 * @api public521 */522523req.__defineGetter__('xhr', function(){524  var val = this.get('X-Requested-With') || '';525  return 'xmlhttprequest' == val.toLowerCase();526});