diff --git a/index.js b/index.js index be6e5b1..5658f2c 100644 --- a/index.js +++ b/index.js @@ -236,16 +236,41 @@ function mimeMatch (expected, actual) { */ function normalizeType (value) { - // parse the type - var type = typer.parse(value) + // Support passing `req-like` or `res-like` objects as argument, + // for backward compatibility. + if (typeof value === 'object') { + value = getcontenttype(value); + } - // remove the parameters - type.parameters = undefined + // Exclude parameters. + var index = value.indexOf(';') + if (index !== -1) { + value = value.slice(0, index) + } + // Content-type headers might use '\t' for whitespace, + // which is not supported by typer.parse, so we must trim. + value = value.trim() + var type = typer.parse(value) // reformat it return typer.format(type) } +/** + * Copied from `media-typer` 0.3.0 + */ +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') + } + + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] + } +} + /** * Try to normalize a type and remove parameters. * diff --git a/test/test.js b/test/test.js index 4443196..1ad2274 100644 --- a/test/test.js +++ b/test/test.js @@ -13,6 +13,11 @@ describe('typeis(req, types)', function () { assert.strictEqual(typeis(req, ['text/*']), 'text/html') }) + it('should support tabs in LWS', function () { + var req = createRequest('text/html\t;\tcharset=utf-8') + assert.strictEqual(typeis(req, ['text/*']), 'text/html') + }) + it('should ignore casing', function () { var req = createRequest('text/HTML') assert.strictEqual(typeis(req, ['text/*']), 'text/html') @@ -301,6 +306,13 @@ describe('typeis.is(mediaType, types)', function () { assert.strictEqual(typeis.is(req, ['jpeg']), false) }) + it('should ignore parameters in content-type header', function () { + var req = createRequest('application/json;\tencoding=utf-8') + + assert.strictEqual(typeis.is(req, ['json']), 'json') + assert.strictEqual(typeis.is(req, ['text']), false) + }) + it('should not check for body', function () { var req = { headers: { 'content-type': 'text/html' } }