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

dont cache unnecessary content types #4134

Merged
merged 1 commit into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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