Skip to content
Myr

request.js

This file

Path

lib/request.js

377 lines · 9.0 KiB · JavaScript

Last changed by

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

History of this file

Take it

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

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 1–14why, 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 , req = http.IncomingMessage.prototype14 , utils = require('./utils')

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

line 15why, one step back
15 , connect = require('connect')

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

line 16why, one step back
16 , parse = require('url').parse

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 17–19why, one step back
17 , mime = require('mime');
1819/**

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 20why, one step back
20 * Default notification formatters.

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 21–22why, one step back
21 */
22

Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe

line 23why, one step back
23var defaultFormatters = exports.formatters = {

misc refactoringTj Holowaychukbefore adoption77d8823

lines 24–25why, one step back
24 s: String
25 , d: function(val){ return val | 0; }

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 26–74why, one step back
26};
2728/**29 * Return request header or optional default.30 *31 * The `Referrer` header field is special-cased,32 * both `Referrer` and `Referer` will yield are33 * interchangeable.34 *35 * Examples:36 *37 * req.header('Content-Type');38 * // => "text/plain"39 * 40 * req.header('content-type');41 * // => "text/plain"42 * 43 * req.header('Accept');44 * // => undefined45 * 46 * req.header('Accept', 'text/html');47 * // => "text/html"48 *49 * @param {String} name50 * @param {String} defaultValue51 * @return {String} 52 * @api public53 */5455req.header = function(name, defaultValue){56 switch (name = name.toLowerCase()) {57 case 'referer':58 case 'referrer':59 return this.headers.referrer60 || this.headers.referer61 || defaultValue;62 default:63 return this.headers[name] || defaultValue;64 }65};6667/**68 * Get `field`'s `param` value, defaulting to ''.69 *70 * Examples:71 *72 * req.get('content-disposition', 'filename');73 * // => "something.png"74 *

examplesTj Holowaychukbefore adoption7eec21a

lines 75–77why, one step back
75 * req.get('content-disposition', 'rawr');
76 * // => ""77 *

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 78–90why, one step back
78 * @param {String} field
79 * @param {String} param80 * @return {String}81 * @api public82 */8384req.get = function(field, param){85 var val = this.header(field);86 if (!val) return '';87 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');88 if (!regexp.exec(val)) return '';89 return RegExp.$1 || RegExp.$2;90};

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

lines 91–92why, one step back
91
92/**

Added `req.secure`Tj Holowaychukbefore adoptionde17b28

lines 93–103why, one step back
93 * Short-hand for `req.connection.encrypted`.
94 *95 * @return {Boolean}96 * @api public97 */9899req.__defineGetter__('secure', function(){100 return req.connection.encrypted;101});102103/**

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

lines 104–112why, one step back
104 * Short-hand for `require('url').parse(req.url).pathname`.
105 *106 * @return {String}107 * @api public108 */109110req.__defineGetter__('path', function(){111 return parse(this.url).pathname;112});

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 113–144why, one step back
113
114/**115 * Check if the _Accept_ header is present, and includes the given `type`.116 *117 * When the _Accept_ header is not present `true` is returned. Otherwise118 * the given `type` is matched by an exact match, and then subtypes. You119 * may pass the subtype such as "html" which is then converted internally120 * to "text/html" using the mime lookup table.121 *122 * Examples:123 * 124 * // Accept: text/html125 * req.accepts('html');126 * // => true127 *128 * // Accept: text/*; application/json129 * req.accepts('html');130 * req.accepts('text/html');131 * req.accepts('text/plain');132 * req.accepts('application/json');133 * // => true134 *135 * req.accepts('image/png');136 * req.accepts('png');137 * // => false138 *139 * @param {String} type140 * @return {Boolean}141 * @api public142 */143144req.accepts = function(type){

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 145–146why, one step back
145 var accept = this.header('Accept')
146 , type = String(type);

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 147why, one step back
147

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 148–150why, one step back
148 // when not present or "*/*" accept anything
149 if (!accept || '*/*' == accept) return true;150

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 151why, one step back
151 // normalize extensions ".json" -> "json"

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

line 152why, one step back
152 if ('.' == type[0]) type = type.substr(1);

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 153why, one step back
153

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 154–155why, one step back
154 // allow "html" vs "text/html" etc
155 if (!~type.indexOf('/')) type = mime.lookup(type);

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 156why, one step back
156

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 157–158why, one step back
157 // check if we have a direct match
158 if (~accept.indexOf(type)) return true;

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 159why, one step back
159

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 160–162why, one step back
160 // check if we have type/*
161 type = type.split('/')[0] + '/*';162 return !! ~accept.indexOf(type);

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 163–183why, one step back
163};
164165/**166 * Return the value of param `name` when present or `defaultValue`.167 *168 * - Checks route placeholders, ex: _/user/:id_169 * - Checks query string params, ex: ?id=12170 * - Checks urlencoded body params, ex: id=12171 *172 * To utilize urlencoded request bodies, `req.body`173 * should be an object. This can be done by using174 * the `connect.bodyParser` middleware.175 *176 * @param {String} name177 * @param {Mixed} defaultValue178 * @return {String}179 * @api public180 */181182req.param = function(name, defaultValue){183 // route params like /user/:id

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 184–186why, one step back
184 if (this.params
185 && this.params.hasOwnProperty(name)186 && undefined !== this.params[name]) {

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 187–189why, one step back
187 return this.params[name];
188 }189 // query string params

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 190–191why, one step back
190 if (undefined !== this.query[name]) return this.query[name];
191

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 192why, one step back
192 // request body params via connect.bodyParser

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 193–194why, one step back
193 if (this.body && undefined !== this.body[name]) return this.body[name];
194

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 195–200why, one step back
195 return defaultValue;
196};197198/**199 * Queue flash `msg` of the given `type`.200 *

Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30

lines 201–202why, one step back
201 * This method is aliased as `req.notify()`.
202 *

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 203–204why, one step back
203 * Examples:
204 *

Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30

line 205why, one step back
205 * req.notify('info', 'email sent');

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

lines 206–208why, one step back
206 * req.notify('info', 'email sent');
207 * req.notify('error', 'email delivery failed');208 * req.notify('info', 'email re-sent');

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 209–210why, one step back
209 * // => 2
210 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 211why, one step back
211 * req.notify('info');

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 212–213why, one step back
212 * // => ['email sent', 'email re-sent']
213 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 214why, one step back
214 * req.notify('info');

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 215–216why, one step back
215 * // => []
216 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 217why, one step back
217 * req.notify();

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 218–222why, one step back
218 * // => { error: ['email delivery failed'], info: [] }
219 *220 * Formatting:221 *222 * Flash notifications also support arbitrary formatting support.

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 223why, one step back
223 * For example you may pass variable arguments to `req.notify()`

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 224–225why, one step back
224 * and use the %s specifier to be replaced by the associated argument:
225 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 226why, one step back
226 * req.notify('info', 'email has been sent to %s.', userName);

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 227why, one step back
227 *

Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe

lines 228–230why, one step back
228 * You may add addition formatters by defining `app.formatters`,
229 * for example in the following snippet we define `%u` to uppercase230 * a string:

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 231why, one step back
231 *

Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe

lines 232–237why, one step back
232 * app.formatters = {
233 * u: function(val){234 * return String(val).toUpperCase();235 * }236 * };237 *

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 238–243why, one step back
238 * @param {String} type
239 * @param {String} msg240 * @return {Array|Object|Number}241 * @api public242 */243

Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30

line 244why, one step back
244req.notify = function(type, msg){

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

lines 245–247why, one step back
245 var sess = this.session;
246 if (null == sess) throw Error('req.notify() requires sessions');247 var msgs = sess.notifications = sess.notifications || {};

refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6

line 248why, one step back
248

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

lines 249–264why, one step back
249 switch (arguments.length) {
250 // flush all messages251 case 0:252 sess.notifications = {};253 return msgs254 // flush messages for a specific type255 case 1:256 var arr = msgs[type];257 delete msgs[type];258 return arr || [];259 // set notification message260 default:261 var i = 2262 , args = arguments263 , formatters = this.app.formatters || {};264 formatters.__proto__ = defaultFormatters;

Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0

line 265why, one step back
265 msg = utils.miniMarkdown(msg);

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

lines 266–267why, one step back
266 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
267 var formatter = formatters[format];

Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0

line 268why, one step back
268 if (formatter) return formatter(utils.escape(args[i++]));

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

lines 269–270why, one step back
269 });
270 return (msgs[type] = msgs[type] || []).push(msg);

refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6

line 271why, one step back
271 }

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 272–300why, one step back
272};
273274/**275 * Check if the incoming request contains the "Content-Type" 276 * header field, and it contains the give mime `type`.277 *278 * Examples:279 *280 * // With Content-Type: text/html; charset=utf-8281 * req.is('html');282 * req.is('text/html');283 * // => true284 * 285 * // When Content-Type is application/json286 * req.is('json');287 * req.is('application/json');288 * // => true289 * 290 * req.is('html');291 * // => false292 * 293 * Ad-hoc callbacks can also be registered with Express, to perform294 * assertions again the request, for example if we need an expressive295 * way to check if our incoming request is an image, we can register "an image"296 * callback:297 * 298 * app.is('an image', function(req){299 * return 0 == req.headers['content-type'].indexOf('image');300 * });

another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d

lines 301–305why, one step back
301 *
302 * app.is('an attachment', function(req){303 * return 0 == req.headers['content-disposition'].indexOf('attachment');304 * });305 *

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 306–328why, one step back
306 * Now within our route callbacks, we can use to to assert content types
307 * such as "image/jpeg", "image/png", etc.308 * 309 * app.post('/image/upload', function(req, res, next){310 * if (req.is('an image')) {311 * // do something312 * } else {313 * next();314 * }315 * });316 * 317 * @param {String} type318 * @return {Boolean}319 * @api public320 */321322req.is = function(type){323 var fn = this.app.is(type);324 if (fn) return fn(this);325 var contentType = this.headers['content-type'];326 if (!contentType) return;327 if (!~type.indexOf('/')) type = mime.lookup(type);328 if (~type.indexOf('*')) {

semiTj Holowaychukbefore adoption82c78ec

line 329why, one step back
329 type = type.split('/');

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 330–335why, one step back
330 contentType = contentType.split('/');
331 if ('*' == type[0] && type[1] == contentType[1]) return true;332 if ('*' == type[1] && type[0] == contentType[0]) return true;333 }334 return !! ~contentType.indexOf(type);335};

Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050

lines 336–361why, one step back
336
337/**338 * Check if the request is fresh, aka339 * Last-Modified and/or the ETag340 * still match.341 *342 * @return {Boolean}343 * @api public344 */345346req.__defineGetter__('fresh', function(){347 return ! this.stale;348})349350/**351 * Check if the request is stale, aka352 * Last-Modified and/or the ETag for the353 * resource has changed.354 *355 * @return {Boolean}356 * @api public357 */358359req.__defineGetter__('stale', function(){360 return connect.utils.modified(this, this.res);361})

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 362–377why, one step back
362
363// Callback for isXMLHttpRequest / xhr364365function isxhr() {366 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';367}368369/**370 * Check if the request was an _XMLHttpRequest_.371 *372 * @return {Boolean}373 * @api public374 */375376req.__defineGetter__('isXMLHttpRequest', isxhr);377req.__defineGetter__('xhr', isxhr);