Skip to content

Commit

Permalink
Add test for content-type overriding inside a plugin (#1434)
Browse files Browse the repository at this point in the history
* Add test for content-type overriding inside a plugin

* Copy default JSON parser from previous content type parser
  • Loading branch information
Marsup authored and mcollina committed Feb 5, 2019
1 parent 772bfbe commit 7bd2a45
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/contentTypeParser.js
Expand Up @@ -190,6 +190,7 @@ function getDefaultJsonParser (onProtoPoisoning) {

function buildContentTypeParser (c) {
const contentTypeParser = new ContentTypeParser()
contentTypeParser._defaultJsonParser = c._defaultJsonParser
Object.assign(contentTypeParser.customParsers, c.customParsers)
contentTypeParser.parserList = c.parserList.slice()
return contentTypeParser
Expand Down
38 changes: 38 additions & 0 deletions test/custom-parser.test.js
Expand Up @@ -537,6 +537,44 @@ test('Can override the default json parser', t => {
})
})

test('Can override the default json parser in a plugin', t => {
t.plan(5)
const fastify = Fastify()

fastify.register((instance, opts, next) => {
instance.addContentTypeParser('application/json', function (req, done) {
t.ok('called')
jsonParser(req, function (err, body) {
done(err, body)
})
})

instance.post('/', (req, reply) => {
reply.send(req.body)
})

next()
})

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

sget({
method: 'POST',
url: 'http://localhost:' + fastify.server.address().port,
body: '{"hello":"world"}',
headers: {
'Content-Type': 'application/json'
}
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(body.toString(), '{"hello":"world"}')
fastify.close()
})
})
})

test('Can\'t override the json parser multiple times', t => {
t.plan(1)
const fastify = Fastify()
Expand Down

0 comments on commit 7bd2a45

Please sign in to comment.