Added `res.respondTo(obj)`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by TJ Holowaychuk · committed by TJ Holowaychuk · parent 892b605 · Browse files · 3 files·+148 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+148 added−6 removed
- tests:+65 added−0 removed
- other:+83 added−6 removed
Provenance
- Commit
b565e25- Tree
e27f45d- Author
TJ Holowaychuk <tj@vision-media.ca>- Committer
TJ Holowaychuk <tj@vision-media.ca>- Parent
892b605
3 files changed+148 added−6 removed
modified:lib/response.js+65 added
12 unmodified lines13 , http = require('http')14 , path = require('path')15 , connect = require('connect')16 , utils = connect.utils17+ , accept = require('./utils').accept18 , statusCodes = http.STATUS_CODES19 , send = connect.static.send20 , mime = require('mime')21 , basename = path.basename265 unmodified lines287 return this.set('Content-Type', mime.lookup(type));288 };289 290 /**291+ * Respond to the Acceptable formats using an `obj`292+ * of mime-type callbacks.293+ *294+ * This method uses `req.accepted`, an array of295+ * acceptable types ordered by their quality values.296+ * When "Accept" is not present the _first_ callback297+ * is invoked, otherwise the first match is used. When298+ * no match is performed the server responds with299+ * 406 "Not Acceptable".300+ *301+ * Examples:302+ *303+ * res.respondTo({304+ * 'text/plain': function(){305+ * res.type('text').send('hey');306+ * },307+ * 308+ * 'text/html': function(){309+ * res.send('<p>hey</p>');310+ * },311+ * 312+ * 'appliation/json': function(){313+ * res.send({ message: 'hey' });314+ * }315+ * });316+ *317+ * @param {Object} obj318+ * @return {ServerResponse} for chaining319+ * @api public320+ */321+322+res.respondTo = function(obj){323+ var keys = Object.keys(obj)324+ , req = this.req325+ , next = req.next326+ , accepted = req.accepted327+ , type328+ , key;329+330+ out:331+ for (var i = 0, len = accepted.length; i < len; ++i) {332+ for (var j = 0, jlen = keys.length; j < jlen; ++j) {333+ if (accept(keys[j].split('/'), accepted[i])) {334+ key = keys[j];335+ break out;336+ }337+ }338+ }339+340+ if (!accepted.length) key = keys.shift();341+342+ if (key) {343+ obj[key](req, res, next);344+ } else {345+ var err = new Error('Not Acceptable');346+ err.status = 406;347+ err.types = keys;348+ next(err);349+ }350+351+ return this;352+};353+354+/**355 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.356 *357 * @param {String} filename358 * @return {ServerResponse}268 unmodified linesmodified:lib/utils.js+18 added-6 removed
50 unmodified lines5152535455555657585912 unmodified lines727374757677787677787980818283848586878889909192939495969798991001011021031049310510610710810912 unmodified lines12212312412511412612712812913045 unmodified lines50 unmodified lines * * @param {String} type * @param {String} str * @return {Boolean} * @api public * @api private */
exports.accepts = function(type, str){ // accept anything when Accept is not present12 unmodified lines , ok;
for (var i = 0; i < len; ++i) { obj = accepted[i]; ok = (type[0] == obj.type || '*' == obj.type) && (type[1] == obj.subtype || '*' == obj.subtype); if (ok) return true; if (exports.accept(type, obj)) return true; }
return false;};
/** * Check if `type` array is acceptable for `other`. * * @param {Array} type * @param {Object} other * @return {Boolean} * @api private */
exports.accept = function(type, other){ return (type[0] == other.type || '*' == other.type) && (type[1] == other.subtype || '*' == other.subtype);};
/** * Parse accept `str`, returning * an array objects containing * `.type` and `.subtype` along * with the values provided by * `parseQuality()`. * * @param {Type} name * @return {Type} * @api public * @api private */
exports.parseAccept = function(str){ return exports12 unmodified lines * `.quality`. * * @param {Type} name * @return {Type} * @api public * @api private */
exports.parseQuality = function(str){ return str45 unmodified linesadded:test/res.respondTo.js+65 added
1+2+var express = require('../')3+ , request = require('./support/http')4+ , utils = require('../lib/utils');5+6+var app = express();7+8+app.use(function(req, res, next){9+ res.respondTo({10+ 'text/plain': function(){11+ res.type('text').send('hey');12+ },13+14+ 'text/html': function(){15+ res.send('<p>hey</p>');16+ },17+ 18+ 'appliation/json': function(){19+ res.send({ message: 'hey' });20+ }21+ });22+});23+24+app.use(function(err, req, res, next){25+ res.send(406, 'Supports: ' + err.types.join(', '));26+})27+28+describe('req', function(){29+ describe('.respondTo(obj)', function(){30+ it('should utilize qvalues in negotiation', function(done){31+ request(app)32+ .get('/')33+ .set('Accept', 'text/html; q=.5, appliation/json, */*; q=.1')34+ .expect('{"message":"hey"}', done);35+ })36+37+ it('should allow wildcard type/subtypes', function(done){38+ request(app)39+ .get('/')40+ .set('Accept', 'text/html; q=.5, appliation/*, */*; q=.1')41+ .expect('{"message":"hey"}', done);42+ })43+44+ describe('when Accept is not present', function(){45+ it('should invoke the first callback', function(done){46+ request(app)47+ .get('/')48+ .expect('hey', done);49+ })50+ })51+52+ describe('when no match is made', function(){53+ it('should should respond with 406 not acceptable', function(done){54+ request(app)55+ .get('/')56+ .set('Accept', 'foo/bar')57+ .end(function(res){58+ res.should.have.status(406);59+ res.body.should.equal('Supports: text/plain, text/html, appliation/json');60+ done();61+ });62+ })63+ })64+ })65+})