Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for HTAB as well as SP as whitespace separators in content-type headers #53

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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