UNPKG

9.89 kBJavaScriptView Raw
1/**
2 * Module dependencies.
3 */
4
5var accepts = require('accepts');
6var typeis = require('type-is');
7var http = require('http');
8var fresh = require('fresh');
9var parseRange = require('range-parser');
10var parse = require('parseurl');
11var proxyaddr = require('proxy-addr');
12
13/**
14 * Request prototype.
15 */
16
17var req = exports = module.exports = {
18 __proto__: http.IncomingMessage.prototype
19};
20
21/**
22 * Return request header.
23 *
24 * The `Referrer` header field is special-cased,
25 * both `Referrer` and `Referer` are interchangeable.
26 *
27 * Examples:
28 *
29 * req.get('Content-Type');
30 * // => "text/plain"
31 *
32 * req.get('content-type');
33 * // => "text/plain"
34 *
35 * req.get('Something');
36 * // => undefined
37 *
38 * Aliased as `req.header()`.
39 *
40 * @param {String} name
41 * @return {String}
42 * @api public
43 */
44
45req.get =
46req.header = function(name){
47 switch (name = name.toLowerCase()) {
48 case 'referer':
49 case 'referrer':
50 return this.headers.referrer
51 || this.headers.referer;
52 default:
53 return this.headers[name];
54 }
55};
56
57/**
58 * To do: update docs.
59 *
60 * Check if the given `type(s)` is acceptable, returning
61 * the best match when true, otherwise `undefined`, in which
62 * case you should respond with 406 "Not Acceptable".
63 *
64 * The `type` value may be a single mime type string
65 * such as "application/json", the extension name
66 * such as "json", a comma-delimted list such as "json, html, text/plain",
67 * an argument list such as `"json", "html", "text/plain"`,
68 * or an array `["json", "html", "text/plain"]`. When a list
69 * or array is given the _best_ match, if any is returned.
70 *
71 * Examples:
72 *
73 * // Accept: text/html
74 * req.accepts('html');
75 * // => "html"
76 *
77 * // Accept: text/*, application/json
78 * req.accepts('html');
79 * // => "html"
80 * req.accepts('text/html');
81 * // => "text/html"
82 * req.accepts('json, text');
83 * // => "json"
84 * req.accepts('application/json');
85 * // => "application/json"
86 *
87 * // Accept: text/*, application/json
88 * req.accepts('image/png');
89 * req.accepts('png');
90 * // => undefined
91 *
92 * // Accept: text/*;q=.5, application/json
93 * req.accepts(['html', 'json']);
94 * req.accepts('html', 'json');
95 * req.accepts('html, json');
96 * // => "json"
97 *
98 * @param {String|Array} type(s)
99 * @return {String}
100 * @api public
101 */
102
103req.accepts = function(){
104 var accept = accepts(this);
105 return accept.types.apply(accept, arguments);
106};
107
108/**
109 * Check if the given `encoding` is accepted.
110 *
111 * @param {String} encoding
112 * @return {Boolean}
113 * @api public
114 */
115
116req.acceptsEncoding = // backwards compatibility
117req.acceptsEncodings = function(){
118 var accept = accepts(this);
119 return accept.encodings.apply(accept, arguments);
120};
121
122/**
123 * To do: update docs.
124 *
125 * Check if the given `charset` is acceptable,
126 * otherwise you should respond with 406 "Not Acceptable".
127 *
128 * @param {String} charset
129 * @return {Boolean}
130 * @api public
131 */
132
133req.acceptsCharset = // backwards compatibility
134req.acceptsCharsets = function(){
135 var accept = accepts(this);
136 return accept.charsets.apply(accept, arguments);
137};
138
139/**
140 * To do: update docs.
141 *
142 * Check if the given `lang` is acceptable,
143 * otherwise you should respond with 406 "Not Acceptable".
144 *
145 * @param {String} lang
146 * @return {Boolean}
147 * @api public
148 */
149
150req.acceptsLanguage = // backwards compatibility
151req.acceptsLanguages = function(){
152 var accept = accepts(this);
153 return accept.languages.apply(accept, arguments);
154};
155
156/**
157 * Parse Range header field,
158 * capping to the given `size`.
159 *
160 * Unspecified ranges such as "0-" require
161 * knowledge of your resource length. In
162 * the case of a byte range this is of course
163 * the total number of bytes. If the Range
164 * header field is not given `null` is returned,
165 * `-1` when unsatisfiable, `-2` when syntactically invalid.
166 *
167 * NOTE: remember that ranges are inclusive, so
168 * for example "Range: users=0-3" should respond
169 * with 4 users when available, not 3.
170 *
171 * @param {Number} size
172 * @return {Array}
173 * @api public
174 */
175
176req.range = function(size){
177 var range = this.get('Range');
178 if (!range) return;
179 return parseRange(size, range);
180};
181
182/**
183 * Return the value of param `name` when present or `defaultValue`.
184 *
185 * - Checks route placeholders, ex: _/user/:id_
186 * - Checks body params, ex: id=12, {"id":12}
187 * - Checks query string params, ex: ?id=12
188 *
189 * To utilize request bodies, `req.body`
190 * should be an object. This can be done by using
191 * the `bodyParser()` middleware.
192 *
193 * @param {String} name
194 * @param {Mixed} [defaultValue]
195 * @return {String}
196 * @api public
197 */
198
199req.param = function(name, defaultValue){
200 var params = this.params || {};
201 var body = this.body || {};
202 var query = this.query || {};
203 if (null != params[name] && params.hasOwnProperty(name)) return params[name];
204 if (null != body[name]) return body[name];
205 if (null != query[name]) return query[name];
206 return defaultValue;
207};
208
209/**
210 * Check if the incoming request contains the "Content-Type"
211 * header field, and it contains the give mime `type`.
212 *
213 * Examples:
214 *
215 * // With Content-Type: text/html; charset=utf-8
216 * req.is('html');
217 * req.is('text/html');
218 * req.is('text/*');
219 * // => true
220 *
221 * // When Content-Type is application/json
222 * req.is('json');
223 * req.is('application/json');
224 * req.is('application/*');
225 * // => true
226 *
227 * req.is('html');
228 * // => false
229 *
230 * @param {String} type
231 * @return {Boolean}
232 * @api public
233 */
234
235req.is = function(types){
236 if (!Array.isArray(types)) types = [].slice.call(arguments);
237 return typeis(this, types);
238};
239
240/**
241 * Return the protocol string "http" or "https"
242 * when requested with TLS. When the "trust proxy"
243 * setting trusts the socket address, the
244 * "X-Forwarded-Proto" header field will be trusted.
245 * If you're running behind a reverse proxy that
246 * supplies https for you this may be enabled.
247 *
248 * @return {String}
249 * @api public
250 */
251
252req.__defineGetter__('protocol', function(){
253 var trust = this.app.get('trust proxy fn');
254
255 if (!trust(this.connection.remoteAddress)) {
256 return this.connection.encrypted
257 ? 'https'
258 : 'http';
259 }
260
261 // Note: X-Forwarded-Proto is normally only ever a
262 // single value, but this is to be safe.
263 var proto = this.get('X-Forwarded-Proto') || 'http';
264 return proto.split(/\s*,\s*/)[0];
265});
266
267/**
268 * Short-hand for:
269 *
270 * req.protocol == 'https'
271 *
272 * @return {Boolean}
273 * @api public
274 */
275
276req.__defineGetter__('secure', function(){
277 return 'https' == this.protocol;
278});
279
280/**
281 * Return the remote address from the trusted proxy.
282 *
283 * The is the remote address on the socket unless
284 * "trust proxy" is set.
285 *
286 * @return {String}
287 * @api public
288 */
289
290req.__defineGetter__('ip', function(){
291 var trust = this.app.get('trust proxy fn');
292 return proxyaddr(this, trust);
293});
294
295/**
296 * When "trust proxy" is set, trusted proxy addresses + client.
297 *
298 * For example if the value were "client, proxy1, proxy2"
299 * you would receive the array `["client", "proxy1", "proxy2"]`
300 * where "proxy2" is the furthest down-stream and "proxy1" and
301 * "proxy2" were trusted.
302 *
303 * @return {Array}
304 * @api public
305 */
306
307req.__defineGetter__('ips', function(){
308 var trust = this.app.get('trust proxy fn');
309 var addrs = proxyaddr.all(this, trust);
310 return addrs.slice(1).reverse();
311});
312
313/**
314 * Return subdomains as an array.
315 *
316 * Subdomains are the dot-separated parts of the host before the main domain of
317 * the app. By default, the domain of the app is assumed to be the last two
318 * parts of the host. This can be changed by setting "subdomain offset".
319 *
320 * For example, if the domain is "tobi.ferrets.example.com":
321 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
322 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
323 *
324 * @return {Array}
325 * @api public
326 */
327
328req.__defineGetter__('subdomains', function(){
329 var offset = this.app.get('subdomain offset');
330 return (this.host || '')
331 .split('.')
332 .reverse()
333 .slice(offset);
334});
335
336/**
337 * Short-hand for `url.parse(req.url).pathname`.
338 *
339 * @return {String}
340 * @api public
341 */
342
343req.__defineGetter__('path', function(){
344 return parse(this).pathname;
345});
346
347/**
348 * Parse the "Host" header field hostname.
349 *
350 * When the "trust proxy" setting trusts the socket
351 * address, the "X-Forwarded-Host" header field will
352 * be trusted.
353 *
354 * @return {String}
355 * @api public
356 */
357
358req.__defineGetter__('host', function(){
359 var trust = this.app.get('trust proxy fn');
360 var host = this.get('X-Forwarded-Host');
361
362 if (!host || !trust(this.connection.remoteAddress)) {
363 host = this.get('Host');
364 }
365
366 if (!host) return;
367
368 // IPv6 literal support
369 var offset = host[0] === '['
370 ? host.indexOf(']') + 1
371 : 0;
372 var index = host.indexOf(':', offset);
373
374 return ~index
375 ? host.substring(0, index)
376 : host;
377});
378
379/**
380 * Check if the request is fresh, aka
381 * Last-Modified and/or the ETag
382 * still match.
383 *
384 * @return {Boolean}
385 * @api public
386 */
387
388req.__defineGetter__('fresh', function(){
389 var method = this.method;
390 var s = this.res.statusCode;
391
392 // GET or HEAD for weak freshness validation only
393 if ('GET' != method && 'HEAD' != method) return false;
394
395 // 2xx or 304 as per rfc2616 14.26
396 if ((s >= 200 && s < 300) || 304 == s) {
397 return fresh(this.headers, this.res._headers);
398 }
399
400 return false;
401});
402
403/**
404 * Check if the request is stale, aka
405 * "Last-Modified" and / or the "ETag" for the
406 * resource has changed.
407 *
408 * @return {Boolean}
409 * @api public
410 */
411
412req.__defineGetter__('stale', function(){
413 return !this.fresh;
414});
415
416/**
417 * Check if the request was an _XMLHttpRequest_.
418 *
419 * @return {Boolean}
420 * @api public
421 */
422
423req.__defineGetter__('xhr', function(){
424 var val = this.get('X-Requested-With') || '';
425 return 'xmlhttprequest' == val.toLowerCase();
426});