Skip to content

Commit

Permalink
improve: dont cache unnecessary content types (#4134)
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak committed Jul 12, 2022
1 parent d6e06c7 commit ed4f4c1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/contentTypeParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,18 @@ ContentTypeParser.prototype.existingParser = function (contentType) {
}

ContentTypeParser.prototype.getParser = function (contentType) {
if (contentType in this.customParsers) {
return this.customParsers[contentType]
}

if (this.cache.has(contentType)) {
return this.cache.get(contentType)
}

// eslint-disable-next-line no-var
for (var i = 0; i !== this.parserList.length; ++i) {
const parserName = this.parserList[i]
if (contentType.indexOf(parserName) > -1) {
if (contentType.indexOf(parserName) !== -1) {
const parser = this.customParsers[parserName]
this.cache.set(contentType, parser)
return parser
Expand Down Expand Up @@ -137,7 +145,7 @@ ContentTypeParser.prototype.remove = function (contentType) {
}

ContentTypeParser.prototype.run = function (contentType, handler, request, reply) {
const parser = this.cache.get(contentType) || this.getParser(contentType)
const parser = this.getParser(contentType)
const resource = new AsyncResource('content-type-parser:run', request)

if (parser === undefined) {
Expand Down
15 changes: 15 additions & 0 deletions test/content-parser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ test('getParser', t => {
t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, third)
})

test('should return matching parser with caching', t => {
t.plan(6)

const fastify = Fastify()

fastify.addContentTypeParser('text/html', first)

t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, first)
t.equal(fastify[keys.kContentTypeParser].cache.size, 0)
t.equal(fastify[keys.kContentTypeParser].getParser('text/html ').fn, first)
t.equal(fastify[keys.kContentTypeParser].cache.size, 1)
t.equal(fastify[keys.kContentTypeParser].getParser('text/html ').fn, first)
t.equal(fastify[keys.kContentTypeParser].cache.size, 1)
})

test('should prefer content type parser with string value', t => {
t.plan(2)

Expand Down

0 comments on commit ed4f4c1

Please sign in to comment.