Skip to content

Commit

Permalink
fixes issue jshttp#52
Browse files Browse the repository at this point in the history
  • Loading branch information
rg2011 committed Jan 28, 2024
1 parent 7d19b7a commit 49189ae
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
33 changes: 29 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
12 changes: 12 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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' } }

Expand Down

0 comments on commit 49189ae

Please sign in to comment.