4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
12 var http = require('http')
13 , req = http.IncomingMessage.prototype
14 , utils = require('./utils')
15 , mime = require('mime');
18 * Default flash formatters.
23 var flashFormatters = exports.flashFormatters = {
30 * Return request header or optional default.
32 * The `Referrer` header field is special-cased,
33 * both `Referrer` and `Referer` will yield are
38 * req.header('Content-Type');
41 * req.header('content-type');
44 * req.header('Accept');
47 * req.header('Accept', 'text/html');
50 * @param {String} name
51 * @param {String} defaultValue
56 req.header = function(name, defaultValue){
57 switch (name = name.toLowerCase()) {
60 return this.headers.referrer
61 || this.headers.referer
64 return this.headers[name] || defaultValue;
69 * Check if the _Accept_ header is present, and includes the given `type`.
71 * When the _Accept_ header is not present `true` is returned. Otherwise
72 * the given `type` is matched by an exact match, and then subtypes. You
73 * may pass the subtype such as "html" which is then converted internally
74 * to "text/html" using the mime lookup table.
78 * // Accept: text/html
79 * req.accepts('html');
82 * // Accept: text/*; application/json
83 * req.accepts('html');
84 * req.accepts('text/html');
85 * req.accepts('text/plain');
86 * req.accepts('application/json');
89 * req.accepts('image/png');
93 * @param {String} type
98 req.accepts = function(type){
99 var accept = this.header('Accept');
101 // normalize extensions ".json" -> "json"
102 if (type && '.' == type[0]) type = type.substr(1);
104 // when Accept does not exist, or is '*/*' return true
105 if (!accept || '*/*' == accept) {
108 // allow "html" vs "text/html" etc
109 if (type.indexOf('/') < 0) {
110 type = mime.lookup(type);
113 // check if we have a direct match
114 if (~accept.indexOf(type)) return true;
116 // check if we have type/*
117 type = type.split('/')[0] + '/*';
118 return accept.indexOf(type) >= 0;
125 * Return the value of param `name` when present or `defaultValue`.
127 * - Checks route placeholders, ex: _/user/:id_
128 * - Checks query string params, ex: ?id=12
129 * - Checks urlencoded body params, ex: id=12
131 * To utilize urlencoded request bodies, `req.body`
132 * should be an object. This can be done by using
133 * the `connect.bodyParser` middleware.
135 * @param {String} name
136 * @param {Mixed} defaultValue
141 req.param = function(name, defaultValue){
142 // route params like /user/:id
143 if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {
144 return this.params[name];
146 // query string params
147 if (undefined !== this.query[name]) {
148 return this.query[name];
150 // request body params via connect.bodyParser
151 if (this.body && undefined !== this.body[name]) {
152 return this.body[name];
158 * Queue flash `msg` of the given `type`.
162 * req.flash('info', 'email sent');
163 * req.flash('error', 'email delivery failed');
164 * req.flash('info', 'email re-sent');
168 * // => ['email sent', 'email re-sent']
174 * // => { error: ['email delivery failed'], info: [] }
178 * Flash notifications also support arbitrary formatting support.
179 * For example you may pass variable arguments to `req.flash()`
180 * and use the %s specifier to be replaced by the associated argument:
182 * req.flash('info', 'email has been sent to %s.', userName);
184 * To add custom formatters use the `exports.flashFormatters` object.
186 * @param {String} type
187 * @param {String} msg
188 * @return {Array|Object|Number}
192 req.flash = function(type, msg){
193 if (this.session === undefined) throw Error('req.flash() requires sessions');
194 var msgs = this.session.flash = this.session.flash || {};
198 , formatters = this.app.flashFormatters || {};
199 formatters.__proto__ = flashFormatters;
200 msg = utils.miniMarkdown(utils.escape(msg));
201 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
202 var formatter = formatters[format];
203 if (formatter) return formatter(args[i++]);
205 return (msgs[type] = msgs[type] || []).push(msg);
207 var arr = msgs[type];
211 this.session.flash = {};
217 * Check if the incoming request contains the "Content-Type"
218 * header field, and it contains the give mime `type`.
222 * // With Content-Type: text/html; charset=utf-8
224 * req.is('text/html');
227 * // When Content-Type is application/json
229 * req.is('application/json');
235 * Ad-hoc callbacks can also be registered with Express, to perform
236 * assertions again the request, for example if we need an expressive
237 * way to check if our incoming request is an image, we can register "an image"
240 * app.is('an image', function(req){
241 * return 0 == req.headers['content-type'].indexOf('image');
244 * Now within our route callbacks, we can use to to assert content types
245 * such as "image/jpeg", "image/png", etc.
247 * app.post('/image/upload', function(req, res, next){
248 * if (req.is('an image')) {
255 * @param {String} type
260 req.is = function(type){
261 var fn = this.app.is(type);
262 if (fn) return fn(this);
263 var contentType = this.headers['content-type'];
264 if (!contentType) return;
265 if (!~type.indexOf('/')) type = mime.lookup(type);
266 if (~type.indexOf('*')) {
267 type = type.split('/')
268 contentType = contentType.split('/');
269 if ('*' == type[0] && type[1] == contentType[1]) return true;
270 if ('*' == type[1] && type[0] == contentType[0]) return true;
272 return ~contentType.indexOf(type);
275 // Callback for isXMLHttpRequest / xhr
278 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';
282 * Check if the request was an _XMLHttpRequest_.
288 req.__defineGetter__('isXMLHttpRequest', isxhr);
289 req.__defineGetter__('xhr', isxhr);