Skip to content

Commit

Permalink
handle duplicate keys
Browse files Browse the repository at this point in the history
  • Loading branch information
kesla committed Aug 27, 2014
1 parent 71f13b1 commit 2fd95af
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 7 deletions.
11 changes: 9 additions & 2 deletions parse-headers.js
Expand Up @@ -11,9 +11,16 @@ module.exports = function (headers) {
trim(headers).split('\n')
, function (row) {
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1))

result[trim(row.slice(0, index)).toLowerCase()] =
trim(row.slice(index + 1))
if (typeof(result[key]) === 'undefined') {
result[key] = value
} else if (Array.isArray(result[key])) {
result[key].push(value)
} else {
result[key] = [ result[key], value ]
}
}
)

Expand Down
47 changes: 42 additions & 5 deletions test.js
@@ -1,31 +1,68 @@
var parse = require('./parse-headers')
var test = require('tape')
, parse = require('./parse-headers')

, headers = [
, headers1 = [
''
, 'Date: Sun, 17 Aug 2014 16:24:52 GMT'
, 'Content-Type: text/html; charset=utf-8'
, 'Transfer-Encoding: chunked'
, ''
]
, headers2 = [
''
, 'Date: Sun, 17 Aug 2014 16:24:52 GMT'
, 'Content-Type: text/html; charset=utf-8'
, 'Transfer-Encoding: chunked'
, 'Set-Cookie: Foo'
, 'set-Cookie: bar'
, 'set-cookie: bong'
]

require('tape')(function (t) {
test('sanity check', function (t) {

t.deepEqual(parse(), {})
t.deepEqual(parse(''), {})
t.end()
})

test('simple', function (t) {
t.deepEqual(
parse(headers1.join('\r\n'))
, {
date: 'Sun, 17 Aug 2014 16:24:52 GMT'
, 'content-type': 'text/html; charset=utf-8'
, 'transfer-encoding': 'chunked'
}
)
t.deepEqual(
parse(headers1.join('\n'))
, {
date: 'Sun, 17 Aug 2014 16:24:52 GMT'
, 'content-type': 'text/html; charset=utf-8'
, 'transfer-encoding': 'chunked'
}
)

t.end()
})

test('duplicate keys', function (t) {
t.deepEqual(
parse(headers.join('\r\n'))
parse(headers2.join('\r\n'))
, {
date: 'Sun, 17 Aug 2014 16:24:52 GMT'
, 'content-type': 'text/html; charset=utf-8'
, 'transfer-encoding': 'chunked'
, 'set-cookie': [ 'Foo', 'bar', 'bong' ]
}
)
t.deepEqual(
parse(headers.join('\n'))
parse(headers2.join('\n'))
, {
date: 'Sun, 17 Aug 2014 16:24:52 GMT'
, 'content-type': 'text/html; charset=utf-8'
, 'transfer-encoding': 'chunked'
, 'set-cookie': [ 'Foo', 'bar', 'bong' ]
}
)

Expand Down

0 comments on commit 2fd95af

Please sign in to comment.