Skip to content

Commit

Permalink
considering extended content-type header format (#62)
Browse files Browse the repository at this point in the history
* considering extended content-type header format

* adding content-type parsing unit tests
  • Loading branch information
jkyberneees authored and mcollina committed Jun 4, 2019
1 parent 4e8718d commit c47969d
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,13 @@ module.exports = fp(function from (fastify, opts, next) {
} else {
// Per RFC 7231 §3.1.1.5 if this header is not present we MAY assume application/octet-stream
const contentType = req.headers['content-type'] || 'application/octet-stream'
body = contentType.toLowerCase() === 'application/json' ? JSON.stringify(this.request.body) : this.request.body
// detect if body should be encoded as JSON
// supporting extended content-type header formats:
// - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
const shouldEncodeJSON = contentType.toLowerCase().indexOf('application/json') === 0
// transparently support JSON encoding
body = shouldEncodeJSON ? JSON.stringify(this.request.body) : this.request.body
// update origin request headers after encoding
headers['content-length'] = Buffer.byteLength(body)
headers['content-type'] = contentType
}
Expand Down
59 changes: 59 additions & 0 deletions test/full-post-extended-content-type.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use strict'

const t = require('tap')
const Fastify = require('fastify')
const From = require('..')
const http = require('http')
const get = require('simple-get')

const instance = Fastify()
instance.register(From)

t.plan(9)
t.tearDown(instance.close.bind(instance))

const target = http.createServer((req, res) => {
t.pass('request proxied')
t.equal(req.method, 'POST')
t.equal(req.headers['content-type'].startsWith('application/json'), true)
var data = ''
req.setEncoding('utf8')
req.on('data', (d) => {
data += d
})
req.on('end', () => {
t.deepEqual(JSON.parse(data), { hello: 'world' })
res.statusCode = 200
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify({ something: 'else' }))
})
})

instance.post('/', (request, reply) => {
reply.from(`http://localhost:${target.address().port}`)
})

t.tearDown(target.close.bind(target))

instance.listen(0, (err) => {
t.error(err)

target.listen(0, (err) => {
t.error(err)

get.concat({
url: `http://localhost:${instance.server.address().port}`,
method: 'POST',
body: JSON.stringify({
hello: 'world'
}),
headers: {
'content-type': 'application/json;charset=utf-8'
}
}, (err, res, data) => {
t.error(err)
t.equal(res.headers['content-type'], 'application/json')
t.deepEqual(JSON.parse(data.toString()), { something: 'else' })
})
})
})

0 comments on commit c47969d

Please sign in to comment.