From 48601ea7d80c6bbea821b90869bd76b091249e5f Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Thu, 28 Nov 2013 12:38:35 -0800 Subject: [PATCH] add matchesMime() util --- lib/request.js | 50 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/lib/request.js b/lib/request.js index 56d3759..b99c373 100644 --- a/lib/request.js +++ b/lib/request.js @@ -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; +}