Permalink
Browse files

Added `req.accepts()` comma-delimited string support

  • Loading branch information...
1 parent 86a9e08 commit d6d16b7899a61cf6772f9d05f1f6bf71a1e7d739 @tj tj committed Mar 24, 2012
Showing with 41 additions and 2 deletions.
  1. +1 −1 lib/utils.js
  2. +13 −0 test/req.accepts.js
  3. +27 −1 test/utils.js
View
2 lib/utils.js
@@ -115,7 +115,7 @@ exports.acceptsArray = function(types, str){
*/
exports.accepts = function(type, str){
- if (!Array.isArray(type)) type = [type];
+ if ('string' == typeof type) type = type.split(/ *, */);
return exports.acceptsArray(type, str);
};
View
13 test/req.accepts.js
@@ -43,6 +43,19 @@ describe('req', function(){
})
})
+ it('should accept a comma-delimited list of types', function(done){
+ var app = express();
+
+ app.use(function(req, res, next){
+ res.end(req.accepts('json, html'));
+ });
+
+ request(app)
+ .get('/')
+ .set('Accept', 'text/html')
+ .expect('html', done);
+ })
+
describe('.accept(types)', function(){
it('should return the first when Accept is not present', function(done){
var app = express();
View
28 test/utils.js
@@ -97,14 +97,40 @@ describe('utils.accepts(type, str)', function(){
.should.equal('text/html');
})
})
-
+
describe('when */* is given', function(){
it('should return the value', function(){
utils.accepts('text/html', 'text/plain, */*')
.should.equal('text/html');
})
})
+ describe('when an array is given', function(){
+ it('should return the best match', function(){
+ utils.accepts(['html', 'json'], 'text/plain, application/json')
+ .should.equal('json');
+
+ utils.accepts(['html', 'application/json'], 'text/plain, application/json')
+ .should.equal('application/json');
+
+ utils.accepts(['text/html', 'application/json'], 'application/json;q=.5, text/html')
+ .should.equal('text/html');
+ })
+ })
+
+ describe('when a comma-delimited list is give', function(){
+ it('should behave like an array', function(){
+ utils.accepts('html, json', 'text/plain, application/json')
+ .should.equal('json');
+
+ utils.accepts('html, application/json', 'text/plain, application/json')
+ .should.equal('application/json');
+
+ utils.accepts('text/html, application/json', 'application/json;q=.5, text/html')
+ .should.equal('text/html');
+ })
+ })
+
describe('when accepting type/subtype', function(){
it('should return the value when present', function(){
utils.accepts('text/html', 'text/plain, text/html')

0 comments on commit d6d16b7

Please sign in to comment.