add matchesMime() util

This commit is contained in:
TJ Holowaychuk 2013-11-28 12:38:35 -08:00
parent 271d921c41
commit 48601ea7d8

View file

@ -514,18 +514,22 @@ module.exports = {
is: function(types){
// no request body
if (!(this.length || 'transfer-encoding' in this.header)) return null;
var ct = this.type;
// request body without a content type?
// no content-type
if (!ct) return false;
// paramless
ct = ct.split(';')[0];
if (!types) return ct;
// ensure array
if (!Array.isArray(types)) types = [].slice.call(arguments);
var type, mt, cts;
for (var i = 0; i < types.length; i++) {
type = types[i];
// exact match
if (type == ct) return type;
// convert to a valid mime type
var type = types[i];
switch (type) {
case 'urlencoded':
mt = 'application/x-www-form-urlencoded';
@ -533,15 +537,10 @@ module.exports = {
default:
mt = ~type.indexOf('/') ? type : mime.lookup(type);
}
// mime types match
if (mt == ct) return type;
// type or subtype match
if (!~type.indexOf('*')) continue;
mt = mt.split('/');
cts = cts || ct.split('/');
if ('*' == mt[0] && mt[1] == cts[1]) return type;
if ('*' == mt[1] && mt[0] == cts[0]) return type;
if (mimeMatch(mt, ct)) return type;
}
// no matches
return false;
},
@ -632,3 +631,26 @@ function extToMime(type) {
if (~type.indexOf('/')) return type;
return mime.lookup(type);
}
/**
* Check if `exected` mime type
* matches `actual` mime type with
* wildcard support.
*
* @param {String} expected
* @param {String} actual
* @return {Boolean}
* @api private
*/
function mimeMatch(expected, actual) {
if (expected == actual) return true;
if (!~expected.indexOf('*')) return false;
actual = actual.split('/');
expected = expected.split('/');
if ('*' == expected[0] && expected[1] == actual[1]) return true;
if ('*' == expected[1] && expected[0] == actual[0]) return true;
}