mirror of
https://github.com/zebrajr/express.git
synced 2026-01-15 12:15:27 +00:00
Added utils.parseAccepts(str)
This commit is contained in:
46
lib/utils.js
46
lib/utils.js
@@ -60,6 +60,52 @@ exports.miniMarkdown = function(str){
|
||||
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse accepts `str`, returning an
|
||||
* object with `.type` and `.quality`.
|
||||
*
|
||||
* @param {Type} name
|
||||
* @return {Type}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
exports.parseAccepts = function(str){
|
||||
return str
|
||||
.split(/ *, */)
|
||||
.map(type)
|
||||
.sort(quality);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse type `str` returning an
|
||||
* object with `.type` and `.quality`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function type(str) {
|
||||
var parts = str.split(/ *; */)
|
||||
, type = parts[0];
|
||||
|
||||
var q = parts[1]
|
||||
? parseFloat(parts[1].split(/ *= */)[1])
|
||||
: 1;
|
||||
|
||||
return { type: type, quality: q };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort by quality.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function quality(a, b) {
|
||||
return b.quality - a.quality;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in the given string of html.
|
||||
*
|
||||
|
||||
@@ -28,4 +28,32 @@ describe('utils.escape(html)', function(){
|
||||
utils.escape('<script>foo & "bar"')
|
||||
.should.equal('<script>foo & "bar"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('utils.parseAccepts(str)', function(){
|
||||
it('should default quality to 1', function(){
|
||||
utils.parseAccepts('text/html')
|
||||
.should.eql([{ type: 'text/html', quality: 1 }]);
|
||||
})
|
||||
|
||||
it('should parse qvalues', function(){
|
||||
utils.parseAccepts('text/html; q=0.5')
|
||||
.should.eql([{ type: 'text/html', quality: 0.5 }]);
|
||||
|
||||
utils.parseAccepts('text/html; q=.2')
|
||||
.should.eql([{ type: 'text/html', quality: 0.2 }]);
|
||||
})
|
||||
|
||||
it('should work with messed up whitespace', function(){
|
||||
utils.parseAccepts('text/html ; q = .2')
|
||||
.should.eql([{ type: 'text/html', quality: 0.2 }]);
|
||||
})
|
||||
|
||||
it('should sort by quality', function(){
|
||||
var str = 'text/plain;q=.2, application/json, text/html;q=0.5';
|
||||
var arr = utils.parseAccepts(str);
|
||||
arr[0].type.should.equal('application/json');
|
||||
arr[1].type.should.equal('text/html');
|
||||
arr[2].type.should.equal('text/plain');
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user