Skip to content
Myr

request.js

This file

Path

lib/request.js

278 lines · 6.8 KiB · JavaScript

Last changed by

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

History of this file

Take it

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 1–13why, 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 , utils = require('./utils')

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

lines 14–15why, one step back
14 , mime = require('connect').utils.mime
15 , req = http.IncomingMessage.prototype;

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 16–51why, one step back
16
17/**18 * Default flash formatters.19 *20 * @type Object21 */2223var flashFormatters = exports.flashFormatters = {24 s: function(val){25 return String(val);26 }27};2829/**30 * Return request header or optional default.31 *32 * Examples:33 *34 * req.header('Content-Type');35 * // => "text/plain"36 * 37 * req.header('content-type');38 * // => "text/plain"39 * 40 * req.header('Accept');41 * // => undefined42 * 43 * req.header('Accept', 'text/html');44 * // => "text/html"45 *46 * @param {String} name47 * @param {String} defaultValue48 * @return {String} 49 * @api public50 */51

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 52why, one step back
52req.header = function(name, defaultValue){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 53–85why, one step back
53 return this.headers[name.toLowerCase()] || defaultValue;
54};5556/**57 * Check if the _Accept_ header is present, and includes the given `type`.58 *59 * When the _Accept_ header is not present `true` is returned. Otherwise60 * the given `type` is matched by an exact match, and then subtypes. You61 * may pass the subtype such as "html" which is then converted internally62 * to "text/html" using the mime lookup table.63 *64 * Examples:65 * 66 * // Accept: text/html67 * req.accepts('html');68 * // => true69 *70 * // Accept: text/*; application/json71 * req.accepts('html');72 * req.accepts('text/html');73 * req.accepts('text/plain');74 * req.accepts('application/json');75 * // => true76 *77 * req.accepts('image/png');78 * req.accepts('png');79 * // => false80 *81 * @param {String} type82 * @return {Boolean}83 * @api public84 */85

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 86why, one step back
86req.accepts = function(type){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 87–128why, one step back
87 var accept = this.header('Accept');
8889 // Normalize extensions ".json" -> "json"90 if (type && '.' == type[0]) type = type.substr(1);9192 // When Accept does not exist, or is '*/*' return true 93 if (!accept || '*/*' == accept) {94 return true;95 } else if (type) {96 // Allow "html" vs "text/html" etc97 if (type.indexOf('/') < 0) {98 type = mime.types['.' + type];99 }100101 // Check if we have a direct match102 if (~accept.indexOf(type)) return true;103104 // Check if we have type/*105 type = type.split('/')[0] + '/*';106 return accept.indexOf(type) >= 0;107 } else {108 return false;109 }110};111112/**113 * Return the value of param `name` when present or `defaultValue`.114 *115 * - Checks route placeholders, ex: _/user/:id_116 * - Checks query string params, ex: ?id=12117 * - Checks urlencoded body params, ex: id=12118 *119 * To utilize urlencoded request bodies, `req.body`120 * should be an object. This can be done by using121 * the `connect.bodyDecoder` middleware.122 *123 * @param {String} name124 * @param {Mixed} defaultValue125 * @return {String}126 * @api public127 */128

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 129why, one step back
129req.param = function(name, defaultValue){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 130–179why, one step back
130 // Route params like /user/:id
131 if (this.params[name] !== undefined) {132 return this.params[name]; 133 }134 // Query string params135 if (this.query[name] !== undefined) {136 return this.query[name]; 137 }138 // Request body params via connect.bodyDecoder139 if (this.body && this.body[name] !== undefined) {140 return this.body[name];141 }142 return defaultValue;143};144145/**146 * Queue flash `msg` of the given `type`.147 *148 * Examples:149 *150 * req.flash('info', 'email sent');151 * req.flash('error', 'email delivery failed');152 * req.flash('info', 'email re-sent');153 * // => 2154 *155 * req.flash('info');156 * // => ['email sent', 'email re-sent']157 *158 * req.flash('info');159 * // => []160 *161 * req.flash();162 * // => { error: ['email delivery failed'], info: [] }163 *164 * Formatting:165 *166 * Flash notifications also support arbitrary formatting support.167 * For example you may pass variable arguments to `req.flash()`168 * and use the %s specifier to be replaced by the associated argument:169 *170 * req.flash('info', 'email has been sent to %s.', userName);171 *172 * To add custom formatters use the `exports.flashFormatters` object.173 *174 * @param {String} type175 * @param {String} msg176 * @return {Array|Object|Number}177 * @api public178 */179

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 180why, one step back
180req.flash = function(type, msg){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 181–246why, one step back
181 var msgs = this.session.flash = this.session.flash || {};
182 if (type && msg) {183 var i = 2184 , args = arguments185 , formatters = this.app.flashFormatters || {};186 formatters.__proto__ = flashFormatters;187 msg = utils.miniMarkdown(utils.htmlEscape(msg));188 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){189 var formatter = formatters[format];190 if (formatter) return formatter(args[i++]);191 });192 return (msgs[type] = msgs[type] || []).push(msg);193 } else if (type) {194 var arr = msgs[type];195 delete msgs[type];196 return arr || [];197 } else {198 this.session.flash = {};199 return msgs;200 }201};202203/**204 * Check if the incoming request contains the "Content-Type" 205 * header field, and it contains the give mime `type`.206 *207 * Examples:208 *209 * // With Content-Type: text/html; charset=utf-8210 * req.is('html');211 * req.is('text/html');212 * // => true213 * 214 * // When Content-Type is application/json215 * req.is('json');216 * req.is('application/json');217 * // => true218 * 219 * req.is('html');220 * // => false221 * 222 * Ad-hoc callbacks can also be registered with Express, to perform223 * assertions again the request, for example if we need an expressive224 * way to check if our incoming request is an image, we can register "an image"225 * callback:226 * 227 * app.is('an image', function(req){228 * return 0 == req.headers['content-type'].indexOf('image');229 * });230 * 231 * Now within our route callbacks, we can use to to assert content types232 * such as "image/jpeg", "image/png", etc.233 * 234 * app.post('/image/upload', function(req, res, next){235 * if (req.is('an image')) {236 * // do something237 * } else {238 * next();239 * }240 * });241 * 242 * @param {String} type243 * @return {Boolean}244 * @api public245 */246

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

line 247why, one step back
247req.is = function(type){

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 248–276why, one step back
248 var fn = this.app.is(type);
249 if (fn) return fn(this);250 var contentType = this.headers['content-type'];251 if (!contentType) return;252 if (!~type.indexOf('/')) type = mime.type('.' + type);253 // TODO: remove when connect no longer appends charset...254 if (~type.indexOf(';')) type = type.split(';')[0];255 if (~type.indexOf('*')) {256 type = type.split('/')257 contentType = contentType.split('/');258 if ('*' == type[0] && type[1] == contentType[1]) return true;259 if ('*' == type[1] && type[0] == contentType[0]) return true;260 }261 return ~contentType.indexOf(type);262};263264// Callback for isXMLHttpRequest / xhr265266function isxhr() {267 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';268}269270/**271 * Check if the request was an _XMLHttpRequest_.272 *273 * @return {Boolean}274 * @api public275 */276

Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7

lines 277–278why, one step back
277req.__defineGetter__('isXMLHttpRequest', isxhr);
278req.__defineGetter__('xhr', isxhr);